this keyword inside function - EventEmitter example

16 views
Skip to first unread message

Ömer

unread,
Jun 18, 2016, 11:24:52 AM6/18/16
to nodejs
Hello, i didn't understand the this keyword in the below code. I know that "The value of this, when used in a function, is the object that "owns" the function.". However, in this code, i can't see any object. What does this refer to in below codes?

Is Radio a function or constructor? How can we understand it?
var Radio = function(station) {
    // what does this refer to?
    
    setTimeout(function() {
        // what does this refer to?
    }); 
this.on('newListener', function(listener) {
        console.log('Event Listener: ' + listener);
    });
};

from the comments : 
// we need to store the reference of `this` to `self`, so that we can use the current context in the setTimeout (or any callback) functions
    // using `this` in the setTimeout functions will refer to those funtions, not the Radio class
but didn't understand

Ryan Schmidt

unread,
Jun 18, 2016, 5:24:05 PM6/18/16
to nod...@googlegroups.com
Radio appears to be a constructor function. On the page you mentioned, it's used like this:

// create an instance of the Radio class
var radio = new Radio(station);

So inside the constructor function, "this" refers to the instance of Radio that's being created.

setTimeout schedules a function to run later. At that later time, the reference to "this" will have been lost. To preserve it, you assign the value of "this" to some other variable before calling setTimeout, then use that other variable inside the function setTimeout will call. So inside the anonymous function that setTimeout calls, "this" no longer refers to the instance of Radio, but "self" does.

These are basic JavaScript object oriented programming concepts, not specific to nodejs.

Reply all
Reply to author
Forward
0 new messages