为什么原型函数的执行上下文(“this”)在本例中是错误的

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

本文关键字:错误 this 函数 原型 执行 上下文 为什么      更新时间:2023-09-26

原型函数bar在Node.js环境中的其他地方执行(bind应该可用)。我希望bar()函数中的this是我的对象的实例:

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 

为什么bar()日志undefinedthis不是我的实例?为什么bind调用没有更改执行上下文?

Function.bind返回一个值-新绑定的函数-但您只是丢弃该值。Function.bind不会更改this(即其调用上下文),也不会更改其参数(this)。

有其他方法可以得到同样的结果吗?

在构造函数内部执行此操作实际上是错误的,因为bar位于Foo.prototype上,因此将其绑定到Foo的任何一个实例都会破坏所有其他Foo.bar调用的this!将其绑定到的意思的位置:

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