Suppose I have JavaScript code like
myClass = function(){
function doSomething(){
alert(this); // this1
}
}
alert(this); //this2
What those two ‘this’ objects are refer for??
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The
thisvalue 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
thisvalue is implicitly set when:Calling a function with no base object reference:
The
thisvalue will also refer to the global object.Calling a function bound as a property of an object:
The
thisvalue will refer toobj.Using the
newoperator:The
thisvalue 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
callorapplymethods, for example:The difference between
callandapplyis that withapply, you can pass correctly any number of arguments, using an Array or anargumentsobject, e.g.:If the first argument value of
callorapplyisnullorundefined, thethisvalue will refer to the global object.(note that this will change in the future, with ECMAScript 5, where
callandapplypass thethisArgvalue without modification)