jquery.each函数是否可能不破坏'这'变量

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

本文关键字:变量 函数 each 是否 jquery      更新时间:2023-09-26

因此,如果变量"this"当前设置为对象,则

{ name: "The old this" }

以下代码将在循环中更改它

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

this.name找不到,而是在循环执行期间将变量"this"设置为与"e"相同

是否可以让jquery在$.each循环中不阻塞这个变量?

如果使用本机.forEach而不是$.each,则可以通过发送第二个参数来设置回调的this值。。。

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

你需要修补旧的浏览器,包括IE8…

  • MDN的兼容性修补程序

或者,您可以使用jQuery的$.proxy返回具有所需this值的函数。。。

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

您可以将this存储到局部变量中,然后在each循环中使用它。试试这个。

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

each循环内,this将指向数组的每个元素。

为了完整起见,还有一个使用原生JS并类似于$.proxy的解决方案是使用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" });

如果您不想更改this,那么只需使用普通的for循环:

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

您无法更改jQuery的.each()的行为。它被编码为设置this.each()迭代器是为了方便起见,因此您应该只在它确实比for循环更方便的时候使用它,而不是在它引起更多麻烦的时候。

其他答案向您展示了如何将this保存到另一个变量。

或者,使用ES6,您可以使用箭头函数声明回调,该函数将忽略jQuery.each()尝试设置的this值,并保留this的词法值。