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

标签 javascript node.js this anonymous-function

原型(prototype)函数 bar 在别处执行,在 Node.js 环境中(bind 应该可用)。我希望 bar() 函数中的 this 成为我的对象的实例:

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 调用没有改变执行上下文?

最佳答案

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

Is there another way to get the same result?

在构造函数内部这样做实际上是错误的,因为bar生活在 Foo.prototype ,因此将其绑定(bind)到 Foo 的任何一个实例会打破 this对于所有其他 Foo.bar电话!将它绑定(bind)在您想要的地方:

module.execute('action', foo.bar.bind(foo));

或者——也许更简单——不定义bar在原型(prototype)上:

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

关于javascript - 为什么这个例子中原型(prototype)函数的执行上下文 ("this") 是错误的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14946201/

相关文章:

javascript - 如何检查我的浏览器是否支持媒体类型?

javascript - 有没有更短的方法来合并重复的对象

node.js - 无法从 Cloud Foundry CLI 登录到 Bluemix Dedicated

node.js - 如何在 Node.js server.listen() 中使用可选的主机名参数

c++ - 在基本构造函数完成之前传递 `this` : UB or just dangerous?

javascript - 使用 jQuery 查找和替换 HTML 字符串

javascript - 在 jquery 追加后或添加 innerHTML 后重绘页面

javascript - 如何从数据库中获取数据到javascript文件中并将其存储在数组中?

java - 对象能否调用 JAXB 将其解码到自身(或 'this' )?

javascript - 为什么 $scope 在 Angular 1.6.1 中不起作用?