On Jun 18, 2016, at 8:59 AM, Ömer wrote:

> 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
> 
> Quoted from : http://www.hacksparrow.com/node-js-eventemitter-tutorial.html

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.

-- 
Job board: http://jobs.nodejs.org/
New group rules: 
https://gist.github.com/othiym23/9886289#file-moderation-policy-md
Old group rules: 
https://github.com/joyent/node/wiki/Mailing-List-Posting-Guidelines
--- 
You received this message because you are subscribed to the Google Groups 
"nodejs" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to nodejs+unsubscr...@googlegroups.com.
To post to this group, send email to nodejs@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/nodejs/85881B2D-1022-49D2-9396-A192B92A9C8D%40ryandesign.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to