Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible for jquery.each function not to clobber the 'this' variable?

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

{ name: "The old this" }

the following code will change it in the loop

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

this.name wont be found, instead the variable "this" is set to the same as 'e' during the loop execution

Is it possible to have jquery not clobber the this variable on $.each loops?

like image 855
arcyqwerty Avatar asked Feb 11 '12 20:02

arcyqwerty


People also ask

What is the use of each() function in jQuery?

each(), which is used to iterate, exclusively, over a jQuery object. The $. each() function can be used to iterate over any collection, whether it is an object or an array. In the case of an array, the callback is passed an array index and a corresponding array value each time.

How to stop each loop in jQuery?

To break a $. each or $(selector). each loop, you have to return false in the loop callback. Returning true skips to the next iteration, equivalent to a continue in a normal loop.

How to loop through an array with jQuery?

Answer: Use the jQuery. each() function each() or $. each() can be used to seamlessly iterate over any collection, whether it is an object or an array. However, since the $. each() function internally retrieves and uses the length property of the passed array or object.


1 Answers

If you use the native .forEach instead of $.each, you can set the this value for the callback by sending a second argument...

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

You'll need to patch older browsers, including IE8...

  • Compatibility patch from MDN

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

$.each(array, $.proxy(function(i, e) {
    alert(this.name);
}, this) );
like image 175
user1106925 Avatar answered Oct 15 '22 19:10

user1106925