Is it possible that the jquery.each function does not compress the variable 'this'?

So, if the variable "this" is currently set to an object,

{ name: "The old this" } 

the following code will change it in a loop

 var array = [1, 2, 3]; $.each(array, function(i, e){ alert(this.name); } ); 

this.name will not be found, instead the variable "this" will be set to 'e' during the execution of the loop

Is it possible that jquery does not knock this variable in $ .each loops?

+4
source share
4 answers

If you use your own .forEach instead of $.each , you can set this to the callback by sending the second argument ...

 array.forEach(function(e, i) { alert(this.name); }, this); 

You will need to fix older browsers, including IE8 ...


Or you can use jQuery $.proxy to return a function with the desired value of this ...

 $.each(array, $.proxy(function(i, e) { alert(this.name); }, this) ); 
+5
source

You can save this to a local variable and then use it inside each loop. Try it.

 var data = this;//where this = { name: "The old this" } var array = [1, 2, 3]; $.each(array, function(i, e){ alert(data.name); } ); 

Inside each this loop will point to each element of the array.

+3
source

If you do not want this be changed, just use the usual for loop:

 var array = [1, 2, 3]; for (var i = 0; i < array.length; i++) { // operate on array[i] alert(this.name); } 

You can do nothing to change the behavior of jQuery .each() . It is encoded to set this . The .each() iterator is understood as convenience - therefore you should use it only when it is really more convenient than the for loop, and not when it causes more problems.

Other answers showed how you can save this to another variable.

0
source

For completeness, another solution using embedded JS and similar to $.proxy is to use Function.prototype.bind :

 // wrapper function to set `this` scope. (function() { $.each([1, 2, 3], (function(i, e) { alert(this.name); }).bind(this)); }).call({ name: "The old this" }); 
0
source

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


All Articles