So this is an awkward question to ask, but I'm learning NodeJS and I have a question. In Java when I call a method from an object, the this
instance remains the same (as in this example).
private Test inst;
public Test() {
inst = this;
this.myFunction();
}
private void myFunction() {
System.out.println(inst == this);
}
This returns true (in theory, that's code off the top of my head). However, in NodeJS when I attempt to do something similar it fails.
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.
}
My question is why is this so, and if this is being done incorrectly on my part, how may I correctly reference other variables in the MyObject instance from the onError method?
“this” Refers to a Global Object The window object is the global object in the case of the browser. And in a NodeJS environment, a special object called global will be the value of this .
In JavaScript, the this keyword refers to an object. Which object depends on how this is being invoked (used or called). The this keyword refers to different objects depending on how it is used: In an object method, this refers to the object.
“This” keyword refers to an object that is executing the current piece of code. It references the object that is executing the current function.
This proves that this here refers to the global object, which is the window object in our case. Note that, if strict mode is enabled for any function then the value of this will be undefined because in strict mode global object refers to undefined in place of the window object.
In JavaScript "methods" are just functions that part of an object.
If you do
var obj = new MyObject();
obj.onError();
The this in onError will be the obj object (because it is the object it is invoked from)
Instead in you case you are passing this.onError to the EventEmitter it will call that function with the EventEmitter (OtherObject) as this.
To avoid that problem use an anonimous function.
var MyObject = function () {
var self = this;
this.other = new OtherObject();
this.other.on("error", function (e) { self.onError(e); });
}
In this way you are binding this back to the object you expect
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With