Suppose I have JavaScript code like
myClass = function(){
function doSomething(){
alert(this); // this1
}
}
alert(this); //this2
What those two 'this' objects are refer for??
Suppose I have JavaScript code like
myClass = function(){
function doSomething(){
alert(this); // this1
}
}
alert(this); //this2
What those two 'this' objects are refer for??
The
this
value in the global execution context, refers to the global object, e.g.:For Function Code, it really depends on how do you invoke the function, for example, the
this
value is implicitly set when:Calling a function with no base object reference:
The
this
value will also refer to the global object.Calling a function bound as a property of an object:
The
this
value will refer toobj
.Using the
new
operator:The
this
value will refer to a newly created object that inherits fromMyFunc.prototype
.Also, you can set explicitly that value when you invoke a function, using either the
call
orapply
methods, for example:The difference between
call
andapply
is that withapply
, you can pass correctly any number of arguments, using an Array or anarguments
object, e.g.:If the first argument value of
call
orapply
isnull
orundefined
, thethis
value will refer to the global object.(note that this will change in the future, with ECMAScript 5, where
call
andapply
pass thethisArg
value without modification)