Why the execution context (“this”) of prototypical function is wrong in this example?

≡放荡痞女 提交于 2019-12-08 02:20:20

问题


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?


回答1:


Function.bind returns a value - the newly bound function - but you just discard that value. Function.bind does not alter this (that is, its invocation context), nor does it alter its arguments (this).

Is there another way to get the same result?

Doing it inside of the constructor function is actually wrong, because bar lives on Foo.prototype, so binding it to any one instance of Foo would break this for all other Foo.bar calls! Bind it where you mean it:

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

Or – maybe even simpler – don't define bar on the prototype at all:

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);


来源:https://stackoverflow.com/questions/14946201/why-the-execution-context-this-of-prototypical-function-is-wrong-in-this-exa

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!