I didn't understand the var self = this; in the below code. I know that "The value of this, when used in a function, is the object that "owns" the function.".Then this keyword inside the object's function refer to that object,right?However the comments of below codes says the opposite of that.
I'm confused about why we cannot use this keyword inside an object's function, in the below code? What does this refer to in below codes?
var util = require('util');
var EventEmitter = require('events').EventEmitter;
// @station - an object with `freq` and `name` properties
var Radio = function(station) {
// 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
var self = this;
// emit 'close' event after 5 secs
setTimeout(function() {
self.emit('close', station);
}, 5000);
// EventEmitters inherit a single event listener, see it in action
this.on('newListener', function(listener) {
console.log('Event Listener: ' + listener);
});
};
// extend the EventEmitter class using our Radio class
util.inherits(Radio, EventEmitter);
// we specify that this module is a refrence to the Radio class
module.exports = Radio;
I read similar posts and understood, however i couldn't understand the comments of below codes. Also, nobody mentioned about the this keyword inside a function's function argument inside a constructor. Especially the second sentence which is written bold makes me confused totaly :
We need to store the reference of
this
toself
, so that we can use the current context in the setTimeout (or any callback) functions. usingthis
in the setTimeout functions will refer to those funtions, not the Radio class
Quoted from : http://www.hacksparrow.com/node-js-eventemitter-tutorial.html