为什么在这个例子中原型函数的执行上下文(“this")是错误的? [英] Why the execution context ("this") of prototypical function is wrong in this example?
问题描述
原型函数 bar
在 Node.js 环境中的其他地方执行(其中 bind
应该可用).我希望 bar()
函数中的 this
成为我的对象的实例:
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
... 为什么 bar()
记录 undefined
而 this
不是我的实例?为什么 bind
调用没有改变执行上下文?
... why bar()
logs undefined
and this
is not my instance? Why the execution context was not changed by the bind
call?
推荐答案
Function.bind
返回一个值 - 新绑定的函数 - 但您只需丢弃该值.Function.bind
不会改变 this
(即它的调用上下文),也不会改变它的参数(this
).
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?
在构造函数内部这样做实际上是错误的,因为 bar
存在于 Foo.prototype
上,所以将它绑定到 Foo的任何一个实例code> 会破坏所有其他
Foo.bar
调用的 this
!将其绑定到意思:
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));
或者——甚至可能更简单——根本不要在原型上定义bar
:
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);
这篇关于为什么在这个例子中原型函数的执行上下文(“this")是错误的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!