What is the reason for declaring var this = this; in javascript?

I stumbled upon this many times on the new code base that I was looking at and wondered if she had any correct reasoning?

+4
source share
3 answers

You can use var that = this; to keep a reference to the current this object when later this will point to something else.

Example ( taken here ):

 $('#element').click(function(){ // this is a reference to the element clicked on var that = this; $('.elements').each(function(){ // this is a reference to the current element in the loop // that is still a reference to the element clicked on }); }); 
+2
source

Sometimes the value of this in JavaScript varies by region. this inside the constructor means something other than this inside the function. Here's a good article on this.

+1
source

If you want to access "this" outside / inside the scope of a specific function call, where "this" can be changed. Just one example that I can think of.

0
source

Source: https://habr.com/ru/post/1483174/


All Articles