2

Prototypical function bar is executed elsewhere, in a Node.js environment (where bind should be available). I want this inside bar() function to be the instance of my object:

var Foo = function (arg) {
    this.arg = arg;

    Foo.prototype.bar.bind(this);
};

Foo.prototype.bar = function () {
    console.log(this); // Not my object!
    console.log(this.arg); // ... thus this is undefined
}

var foo = new Foo();
module.execute('action', foo.bar); // foo.bar is the callback 

... why bar() logs undefined and this is not my instance? Why the execution context was not changed by the bind call?

4

1 に答える 1

6

Function.bind値 (新しくバインドされた関数) を返しますが、その値を破棄するだけです。(つまり、その呼び出しコンテキスト) も、その引数 ( ) も変更しませFunction.bindん。thisthis

同じ結果を得る別の方法はありますか?

コンストラクター関数内で実行するのは実際には間違っbarFoo.prototypeいます。意図した場所にバインドしますFoothisFoo.bar

module.execute('action', foo.bar.bind(foo));

あるいは、もっと簡単かもしれませんbarが、プロトタイプではまったく定義しないでください:

var Foo = function (arg) {
    this.arg = arg;

    function bar () {
        console.log(this);
        console.log(this.arg);
    }

    this.bar = bar.bind(this);
};

var foo = new Foo();
module.execute('action', foo.bar);
于 2013-02-18T22:10:08.220 に答える