Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebug console window scope. Why isn't "this" always the same?

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

like image 674
André Pena Avatar asked Nov 26 '09 13:11

André Pena


3 Answers

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.

like image 195
AnthonyWJones Avatar answered Oct 23 '22 23:10

AnthonyWJones


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

like image 35
rahul Avatar answered Oct 23 '22 21:10

rahul


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

like image 28
Steerpike Avatar answered Oct 23 '22 23:10

Steerpike