原型函数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
返回一个值-新绑定的函数-但您只是丢弃该值。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);