Re:“This” in JavaScript
by no_gravity on Monday December 08, 2014 @04:03AM
(#8715572)
Can this model explain what "this" is in the context of an event handler?
http://jsfiddle.net/5bh7yot5/
[ Parent
| on HN ]
Easily.
But first, let me fix some errors in your code.
You probably meant to write syntactically correct code, so first line changes to following:
o={ f: function() { setTimeout(1000,console.log(this)) } }
Then, you probably meant to call console.log after one second, not running it immediately and passing result to timeout argument, and passing 1000 as a callback argument.So the code changes to:
o={ f: function() { setTimeout(function() { console.log(this); }, 1000); } }
o.f()
Okay. So what happens now is that- You create and object with property 'f'
- You call the function stored within that property
- Within Execution Context of that function call, `this` is going to be equal to our object. Note that we have not yet used `this`.
- We call setTimeout, passing it function as a callback.
- After one second, that function is called, with new Execution Context, not equal to the first one. `this` there is equal to global scope variable.
Re:“This” in JavaScript
by zenojevski on Monday December 08, 2014 @04:26AM
(#8715631)
The way you've written this code, `this` refers to `o`, as it has been evaluated at the time of execution of `f()` (first case) rather than inside the `setTimeout` callback, at which point it'd be `Window` (second case). So yes.
Basically your code is doing this right now:
o.f = function(){
console.log(this); // logs `o`, returns `undefined`
setTimeout(1000, undefined);
});
If you did this: o.f = function(){
setTimeout(1000, function(){
console.log(this);
});
};
Then it'd be `Window` as in rule #2.