Reputation: 41919
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();
Upvotes: 4
Views: 8289
Reputation: 8689
To add to the other answers:
When a function is called, this
is set depending on how it's called. If it's called with myfunc.call
or myfunc.apply
, then this
is set to the first passed argument. If it's called in the 'dotted' form, i.e. myObject.myfunc()
then this
is set to whatever is before the dot.
There is an exception to this rule, which is that it's possible to bake the value of this
in with bind
, in which case it will be whatever has been bound. i.e. in var boundfunc = myfunc.bind(myobj);
then any time boundfunc
is called, it would be like calling myfunc
but with this
referring to myobj
regardless of anything else. Here's an example that does that:
function F() {
var C = function() {
return this;
}.bind(this);
return C();
}
var o = new F();
If none of these cases are applicable, then this
is always either the global object (window
if you're in a browser), or, if you're in strict mode it's undefined
.
Upvotes: 0
Reputation: 816364
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();
}
Upvotes: 11
Reputation: 141869
this
refers to the global object in your program. To get this
to reference the instance of F
, try,
function F() {
function C() {
return this;
}
return C.call(this); // call C with the object of F as a context
}
var o = new F();
On Chrome, you could simply enter the variable to inspect, and its value will get logged. It's similar to doing a console.log(object)
, but much easier to work with. Here's a screenshot of running this code sample in Chrome. The value of the last statement o
is automatically printed, and I printed it once again, just to be sure. It logged DOMWindow
which refers to the global window object on the browser.
Upvotes: 2