【问题标题】:Why the execution context ("this") of prototypical function is wrong in this example?为什么在这个例子中原型函数的执行上下文(“this”)是错误的?
【发布时间】: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() 记录undefinedthis 不是我的实例?为什么 bind 调用没有改变执行上下文?

【问题讨论】:

  • 除了Matt所说的,每次你调用Foo你都会绑定一个不同的this。如果您将函数调用为foo.bar,为什么还要使用bind?此外,this 不是“上下文”,它是函数的一个特殊值,是其 execution context 的一个参数,以及所有其他变量和作用域链。

标签: javascript node.js this anonymous-function


【解决方案1】:

Function.bind 返回一个值 - 新绑定的函数 - 但您只需丢弃该值。 Function.bind 不会改变this(即它的调用上下文),也不会改变它的参数(this)。

还有其他方法可以获得相同的结果吗?

在构造函数内部执行它实际上是错误的,因为bar 存在于Foo.prototype 上,因此将其绑定到Foo 的任何一个实例都会破坏this 的所有其他Foo.bar 调用!将它绑定到你意思的地方:

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);

【讨论】:

  • 即我需要赋值返回值?有没有其他方法可以获得相同的结果?我不喜欢重新分配功能的想法......
  • 我会花一些时间来完全理解你的答案,同时......真的谢谢你!
猜你喜欢
  • 2016-01-03
  • 1970-01-01
  • 2020-01-29
  • 1970-01-01
  • 1970-01-01
  • 2012-06-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多