原型(prototype)函数 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()
记录 undefined
而 this
不是我的实例?为什么 bind
调用没有改变执行上下文?
最佳答案
Function.bind
返回一个值——新绑定(bind)的函数——但你只是丢弃了那个值。 Function.bind
不会改变 this
(即它的调用上下文),也不会改变它的参数(this
)。
Is there another way to get the same result?
在构造函数内部这样做实际上是错误的,因为bar
生活在 Foo.prototype
,因此将其绑定(bind)到 Foo
的任何一个实例会打破 this
对于所有其他 Foo.bar
电话!将它绑定(bind)在您想要的地方:
module.execute('action', foo.bar.bind(foo));
或者——也许更简单——不定义bar
在原型(prototype)上:
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);
关于javascript - 为什么这个例子中原型(prototype)函数的执行上下文 ("this") 是错误的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14946201/