Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript global object?

Tags:

javascript

Does the value of "this" refer to the global object or the object "o" in the program below?

More importantly, what code could I run to test what the reference of "this" is?

function F() { 
    function C() { 
        return this;
    } 
    return C();
} 

var o = new F();
like image 237
Leahcim Avatar asked Dec 13 '22 14:12

Leahcim


1 Answers

It refers to the global object (window).

Edit: Actually, it will refer to both, the global object and o, because they are the same. o will have a reference to the object returned from F() which is the object returned from C() which is the window object ;)

You can call console.log(this) to find out which object it refers to. It should give you a listing of all the methods of the object on the console and you should be able to infer from this which object it is.
For this to work in Firefox, you need Firebug. Don't know for IE.

Update:

@Anurag already showed you how to explicitly set this. If you just want to refer to this of a higher scope, you have to assign it to a variable explicitly. Example:

function F() {
    var that = this; 
    function C() { 
        console.log(that);
    } 
    C();
}
like image 89
Felix Kling Avatar answered Dec 29 '22 14:12

Felix Kling