views:

67

answers:

3

Firebug console scope. Why isn't "this" always the same? Shoudn't it be "window" all the time?

+3  A: 

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() or objname['myFunction'](), causes the value of this to be objname.

See more abot calling functions in JavaScript

JavaScript, 5 ways to call a function

rahul
This answer accurate as it is doesn't actually address the question as it relates to the console behaviour.
AnthonyWJones
+3  A: 

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:

alt text

Steerpike
+2  A: 

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.

AnthonyWJones
thanks for you answer.. but, a question: If I'm not stuck in a breakpoint, can "this" be other than window in the console?
Ciwee