Nodejs - What is this this?

So this is an uncomfortable question, 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 (theoretically, this code is from the top of my head). However, in NodeJS, when I try to do something like this, 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 it does not work correctly on my part, how can I correctly refer to other variables in the MyObject instance from the onError method?

+6
source share
2 answers

In JavaScript, β€œmethods” are simply functions that are part of an object.

If you do

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

This in onError will be an obj object (because it is the object from which it is called)

Instead, in this case, you pass this.onError to an EventEmitter, it will call this function with an EventEmitter (OtherObject) like this.

To avoid this problem, use an anonymous function.

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

This way you bind this back to the expected object

+6
source

There is an easier way - you can use the bind function.

 var EventEmitter = require('events').EventEmitter; var MyObject = function () { this.other = new EventEmitter(); this.other.on("error", this.onError.bind(this)); console.log(1, this instanceof MyObject); // 1, true }; MyObject.prototype.onError = function (e) { console.log(2, this instanceof MyObject); // 2, true }; MyObject.prototype.callError = function (e) { console.log(3, this instanceof MyObject); // 3, true this.other.emit('error', e); }; var mo = new MyObject(); mo.callError(new Error(1)); 

Demo

0
source

All Articles