所以这是一个尴尬的问题,但我正在学习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实例中的其他变量?