1

次のパターンに従って、プロジェクトで名前空間を使用しています。

// simply a namespace attic object
// parent to my worker objects
;(function( RoaringSky, undefined ) 
{
    var opt = {
        backend : ""
    },
    name = ""
    ;

    RoaringSky.init = function( options ) {
       jQuery.extend(opt,options);
       console.log( 'RoaringSky.init complete');
    };
    // accessor 
    RoaringSky.opt = opt;

})(window.RoaringSky = window.RoaringSky || {});

そして、この名前空間の子オブジェクトは次のようになります:

RoaringSky.Day = (function() {

    // constructor
    var Day = function(){

        var id = "none";
        var name = "none";
        var date = "none";
        var periods = new Array();

        this.periods = function() {
            return periods;
        };
    };

    // invoking day.time() fails - is not a function message
    Day.prototype.time = function() {
        return this.doSomthingWithDate(date);
    };


    return Day;
})(window.RoaringSky.Day = window.RoaringSky.Day || {});

パターンはそれが行く限りうまくいくと思います。(批判歓迎) しかし、プロトタイプ プロパティの使用を阻止しているようです。

私の理解は不完全かもしれませんが(確かにそうです)、私の知る限り、オブジェクトを作成したら(上記の Day クラスのように)、次の方法で関数を記述できるはずです。

Day.prototype.time = function() {
    return this.doSomthingWithDate(date);
};

クラスのすべてのインスタンスは、コンストラクターのクラス オブジェクト Day() のプロパティであるため、関数を継承します。

ただし、これを試すと:

var day = new Day();
day = new Date();
console.log( 'day.time: '+ day.time() );

祝福された「day.time() は関数ではありません」というエラー メッセージが返されます。

私は何を間違っていますか?これは私を夢中にさせ始めています。

  • エリック
4

1 に答える 1

0

カップルの問題:

RoaringSky.Day = (function() {

    // constructor
    var Day = function(){

        var id = "none";
        var name = "none";
        var date = "none";
        var periods = new Array();

        this.periods = function() {
            return periods;
        };
    };

    // invoking day.time() fails - is not a function message
    Day.prototype.time = function() {
        // can't use "date" here since it is not in scope
        return this.doSomthingWithDate(date);
    };


    return Day;
})(window.RoaringSky.Day = window.RoaringSky.Day || {});

それで:

var day = new Day(); // Day is not a member of window, so this will only work when used in the `RoaringSky.Day` declaration.
day = new Date();    // you then override the day variable for some reason
console.log( 'day.time: '+ day.time() ); // time is not a function member of Date
于 2013-02-14T20:39:06.393 に答える