javascript - nodejs - 这是哪个 "this"?

标签 javascript node.js

所以这是一个尴尬的问题,但我正在学习 NodeJS,我有一个问题。在 Java 中,当我从对象调用方法时,this 实例保持不变(如本例所示)。

private Test inst;
public Test() {
    inst = this;
    this.myFunction();
}

private void myFunction() {
    System.out.println(inst == this);
}

这会返回 true(理论上,这是我头脑中的代码)。但是,在 NodeJS 中,当我尝试做类似的事情时失败了。

var MyObject = function () {
    this.other = new OtherObject();
    this.other.on("error", this.onError);
    console.log(this); //This returns the MyObject object
}

MyObject.prototype.onError = function (e) {
    console.log(this); //This returns the OtherObject object, where I thought it would return the MyObject object.
}

我的问题是为什么会这样,如果我的操作不正确,我如何从 onError 方法正确引用 MyObject 实例中的其他变量?

最佳答案

在 JavaScript 中,“方法”只是对象的一部分的函数。

如果你这样做

var obj = new MyObject();
obj.onError();

onError 中的 this 将是 obj 对象(因为它是调用它的对象)

相反,在您将 this.onError 传递给 EventEmitter 的情况下,它会像这样使用 EventEmitter (OtherObject) 调用该函数。

为避免该问题,请使用匿名函数。

var MyObject = function () {
    var self = this;
    this.other = new OtherObject();
    this.other.on("error", function (e) { self.onError(e); });
}

通过这种方式,您将 this 绑定(bind)回您期望的对象

关于javascript - nodejs - 这是哪个 "this"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31179491/

相关文章:

node.js - 蒙戈错误: cursor is dead (mongo node driver)

javascript - 在后面的代码中获取内部 html 值(C#)

node.js - node-sqlite 插入在非空约束上失败,但数据在那里?

javascript - 使用 JS 操作对象

javascript - 解析调试器关键字

node.js - 请求无效,错误 : Invalid protocol: 127. 0.0.1 :?

node.js - 如何在没有 sudo 的情况下运行 NPM?

node.js - bcrypt.compare() 验证密码时始终返回 false

javascript - 带 for 循环的嵌套 Promise 不起作用

javascript - 用 enzyme 和 connect() 进行开 Jest 测试,给出 `import connectAdvanced from ' ../components/connectAdvanced';`