dup*_*r51 6 javascript node.js
所以这是一个尴尬的问题,但我正在学习NodeJS,我有一个问题.在Java中,当我从一个对象调用一个方法时,该this实例保持不变(如本例所示).
private Test inst;
public Test() {
inst = this;
this.myFunction();
}
private void myFunction() {
System.out.println(inst == this);
}
Run Code Online (Sandbox Code Playgroud)
这返回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.
}
Run Code Online (Sandbox Code Playgroud)
我的问题是为什么会这样,如果我这样做不正确,我怎样才能从onError方法正确引用MyObject实例中的其他变量?
在JavaScript中,"方法"只是对象的一部分.
如果你这样做
var obj = new MyObject();
obj.onError();
Run Code Online (Sandbox Code Playgroud)
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); });
}
Run Code Online (Sandbox Code Playgroud)
通过这种方式,您可以将其绑定到您期望的对象