【发布时间】:2013-02-18 22:08:34
【问题描述】:
原型函数 bar 在其他地方执行,在 Node.js 环境中(bind 应该可用)。我希望 this 内的 bar() 函数成为我的对象的实例:
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 调用没有改变执行上下文?
【问题讨论】:
-
除了Matt所说的,每次你调用
Foo你都会绑定一个不同的this。如果您将函数调用为foo.bar,为什么还要使用bind?此外,this不是“上下文”,它是函数的一个特殊值,是其 execution context 的一个参数,以及所有其他变量和作用域链。
标签: javascript node.js this anonymous-function