Node.js setting 'this' when running a function


I'm creating a module in Node.js that has an exported class function constructor. I added 2 prototyped functions to that class but I also have a bunch of free standing functions.

The plain functions I use as handlers for events and callbacks internally to the class. I don't want to expose those functions as part of the classes prototype.

In the chaining of the free standing functions I want to reference the main class that the module is built around so I can emit events (I used util.inherits(myclassconsructor, EventEmitter)). But in my inner functions this is not correct. I tried making a global variable to the module called self and did self = this as the first line of the constructor.

I then checked that if I did self.on("message name", function() {console.log("worked")}); that it did indeed work.

Then I went to my main module which constructs the module in question and created the above module and bound to the same event. I don't receive the event outside the module...

Module A

var self;
function A() {
  self = this;
  self.on('message name', function() { console.log('test') }); // Firing
function doStuff() {
function callback() {
  self.emit('message name');

Module B

var a = new A();
a.on('message name', domystuff);  // Not firing
function domystuff() {
  console.log('my stuff');

Found this thread which seems to be the issue I'm having but I'm not able to reproduce results. node.js eventEmitter + http.request

Problem courtesy of: Erock 634


IF I understand correctly, you want to use:;

instead. The the call function will call the function it is called upon, and set this to the first parameter.

See the documentation at Mozilla MDN

As for your callback issue I might be tempted to restructure you code like this...

var inst = this;
api.callApi(function(p1,p2,p3) { inst.emit('message name',p1,p2,p3); });

But there are slightly more elegant methods.

Solution courtesy of: Forbesmyester


There is currently no discussion for this recipe.

This recipe can be found in it's original form on Stack Over Flow.