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();
It refers to the global object (
window).Edit: Actually, it will refer to both, the global object and
o, because they are the same.owill have a reference to the object returned fromF()which is the object returned fromC()which is thewindowobject 😉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 tothisof a higher scope, you have to assign it to a variable explicitly. Example: