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?
If you use the native
.forEachinstead of$.each, you can set thethisvalue for the callback by sending a second argument…You’ll need to patch older browsers, including IE8…
Or you can use jQuery’s
$.proxyto return a function with the desiredthisvalue…