简体   繁体   English

jquery.each 函数是否有可能不破坏“this”变量?

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

So if the variable "this" is currently set to an object,所以如果变量“this”当前被设置为一个对象,

{ 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不会找到 this.name,而是在循环执行期间将变量“this”设置为与“e”相同

Is it possible to have jquery not clobber the this variable on $.each loops?是否有可能让 jquery 不破坏 $.each 循环上的 this 变量?

If you use the native .forEach instead of $.each , you can set the this value for the callback by sending a second argument...如果您使用本机.forEach而不是$.each ,您可以通过发送第二个参数来设置回调的this值...

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

You'll need to patch older browsers, including IE8...您需要修补旧版浏览器,包括 IE8...


Or you can use jQuery's $.proxy to return a function with the desired this value...或者您可以使用 jQuery 的$.proxy返回一个具有所需this值的函数...

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

You can store this into a local variable and then use it inside each loop.您可以存储this为一个局部变量,然后用它里面each循环。 Try this.试试这个。

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

Inside each loop this will point to each element of the array.each循环中, this将指向数组的每个元素。

For completeness, one more solution, using native JS and similar to $.proxy , is to use Function.prototype.bind :为了完整$.proxy ,使用原生 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" });

If you don't want this to be changed, then just use a normal for loop:如果你不想this被改变,那么就使用一个正常for循环:

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

There is nothing you can do to change the behavior of jQuery's .each() .您无法改变 jQuery 的.each()的行为。 It is coded to set this .它被编码来设置this The .each() iterator is meant as a convenience - thus you should only use it when it is indeed more convenient than the for loop, not when it causes more trouble. .each()迭代器是为了方便——因此你应该只在它确实比for循环更方便时才使用它,而不是当它引起更多麻烦时。

The other answers have shown you how you can save this to another variable.其他答案显示你如何可以保存this另一个变量。

Or, with ES6, you can declare your callback using an arrow function that will then ignore the this value that jQuery.each() tries to set and will keep the lexical value of this .或者,在 ES6 中,您可以使用箭头函数声明回调,该函数将忽略jQuery.each()尝试设置的this值并保留this的词法值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM