In a JavaScript file I saw:
function Somefunction(){
var that = this;
...
}
What is the purpose of declaring that and assigning this this to it?
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.
I’m going to begin this answer with an illustration:
My answer originally demonstrated this with jQuery, which is only very slightly different:
Because
thisfrequently changes when you change the scope by calling a new function, you can’t access the original value by using it. Aliasing it tothatallows you still to access the original value ofthis.Personally, I dislike the use of
thatas the alias. It is rarely obvious what it is referring to, especially if the functions are longer than a couple of lines. I always use a more descriptive alias. In my examples above, I’d probably useclickedEl.