Firebug console window scope. Why isn't "this" always the same?
The value of this
in the console will be the same as the value of this
in the code currently being executed. Consider:-
function outer()
{
// this is window
var x = {n:12};
var fn = function()
{
// this is object {n:12}
alert(this.n);
}
fn.call(x);
}
...
<img src="thing.gif" onclick="outer()" />
If you put a break point on the x = {n:12}
line, switch to console you will find the this
is the window. However when you step to the alert
line this
in the console is the object held by the x
variable. IOW there is no distinction between this
in the executing context and the console. Its for this reason that you can use the console to tweak values of variables and properties while debugging.
In a function called directly without an explicit owner object, causes the value of this to be the default object (window in the browser).
In a function called using the method invocation syntax, like
objname.myFunction()
orobjname['myFunction']()
, causes the value of this to be objname.
See more abot calling functions in JavaScript
JavaScript, 5 ways to call a function
The this
keyword always refers to the owner of the function being called. You can read a clear and detailed explanation on it here.
From the article I linked above this image I think explains it most clearly: