所以这是一个尴尬的问题,但我正在学习 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/