0

複数レベルのメソッドとプロパティを持つオブジェクトが必要です。最上位にはプロパティとメソッドがあります。これらのプロパティの一部は、第 2 レベルのメソッドとプロパティの名前空間として機能します。

例えば

//first level methods
base.doStuff();
base.doMore();

//second level methods
base.level2.doStuff();

最初のレベルを行うのは簡単です:

function Base(foo) {
    this.foo = foo;
}

Base.prototype.doStuff = function () {
    console.log(this.foo);
}

Base.prototype.doMore = function () {
    console.log(this.foo);
}

base = new Base("bar");
base.doStuff();

関数式で「this」キーワードが Base コンストラクターを指す 2 番目のレベルを取得することは可能ですか?

4

3 に答える 3

0

良い、

base.doStuff();

doStuffのコンテキストで呼び出していますbase。と同じです

base.doStuff.call(base);

オーバーライドするためにcall、任意の関数を使用できます。applythis

var base = new Base();

var someFun = function () {
    console.log (this === base); // true
};

someFun.call(base);

さらなる匿名の例:

var anObj = {
    method0: function () {
        console.log (this === anObj); // true
    }
};

anObj.method1 = function () {
    console.log (this === anObj); // true
};

anObj.method0();
anObj.method1();

したがって、「第 2 レベル」は、「第 1 レベル」オブジェクトではなく、 をthis指します。level2

于 2013-09-04T19:27:13.033 に答える
0

これは非常に悪い考えですが、次のようになります。

function Base() {
    this.name = 'Base';
    this.level2 = new Level2(this);
}

Base.prototype.whatsMyName = function(){
    alert(this.name);
};

function Level2(base) {
    this.name='Level2';
    for(var func in Level2.prototype) {
        this[func] = Level2.prototype[func].bind(base);
     }
}

Level2.prototype.whatsMyName = function(){
    alert(this.name);
};

var b = new Base();

b.whatsMyName(); //Base
b.level2.whatsMyName(); //Also Base

ここで実行されていることがわかります: http://jsfiddle.net/zLFgd/1/

于 2013-09-04T20:02:51.630 に答える