为什么原型函数的执行上下文("this")在这个例子中是错误的?

gre*_*emo 2 javascript this anonymous-function node.js

原型函数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 
Run Code Online (Sandbox Code Playgroud)

...为什么bar()日志undefinedthis不是我的实例?为什么bind调用不会改变执行上下文?

Mat*_*all 6

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

有没有其他方法可以得到相同的结果?

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

module.execute('action', foo.bar.bind(foo));
Run Code Online (Sandbox Code Playgroud)

或者 - 甚至可能更简单 - 根本不在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);
Run Code Online (Sandbox Code Playgroud)