为什么原型函数的执行上下文(“this”)在这个例子中是错误的? [英] Why the execution context ("this") of prototypical function is wrong in this example?
问题描述
原型函数 bar
在Node.js环境中的其他地方执行(其中 bind
应该可用。我希望 这个
里面的 bar()
函数作为我的对象的实例:
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()
logs undefined
和此
不是我的实例?为什么执行上下文没有被 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
不会改变这个
(也就是它的调用上下文),也不会改变它的参数(此
)。
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
的任何一个实例都会破坏这个
用于所有其他 Foo.bar
来电!将它绑定在意为的地方:
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 $ c原型上的$ c>:
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屋!