简体   繁体   English

有关prototype.js .each方法的匿名函数中的“ this”的问题

[英]Question regarding “this” inside anonymous function of prototype.js .each method

I've been searching for hours for a solution to this problem. 我一直在寻找解决这个问题的方法。 I'm creating a table using prototype.js 1.6.0.1 and am having trouble with the this object in context with the .each function. 我正在使用prototype.js 1.6.0.1创建一个表,并且在使用.each函数的上下文中遇到此对象有麻烦。 here is a snippit. 这是一个摘录。

var Table = Class.create({
  initialize : function(id) {
    this.elmnt = $(id);
    this.rows = [];
  },
  initRows : function() {
    $A(this._elmnt.tBodies).each(function(body) {
      $A(body.rows).each(function(row) {
        //right here is where i would like to call
        // this.rows.push(row);
        console.log(this); // prints DOMWindow
      });
    });
  }
});

As you can see inside the second .each function this resolves to DOMWindow. 正如您在第二个.each函数内部看到的那样,该函数解析为DOMWindow。 I would like to be able to call this.rows.push(row) but I can't as "this" isn't resolving as expected. 我希望能够调用this.rows.push(row)但我无法这样做,因为“ this”未按预期解决。

Any help would be appreciated. 任何帮助,将不胜感激。 I know i could do the standard (i=0; i < length; i++) loop but I was trying to make this a little cleaner. 我知道我可以执行标准的(i = 0; i <length; i ++)循环,但是我正在尝试使其更加简洁。 Thanks for any guidance you can offer. 感谢您提供的任何指导。

The easiest way to work around this is to save this at the start of initRows and refer to in within the each functions 要解决这个最简单的方法是保存this在开始initRows和内指的是each功能

initRows : function() {
    var self = this;
    $A(this._elmnt.tBodies).each(function(body) {
      $A(body.rows).each(function(row) {
        //right here is where i would like to call
        self.rows.push(row);
        console.log(self); // prints DOMWindow
      });
    });
  }

The problem you're running into is that this can be manipulated by the caller of the function. 您正在运行到的问题是, this可以通过函数的调用者进行操作。 It's very common in callbacks to set this to an element which is relevant to the call back. 这是很常见的回调来设置this到是有关回调的元素。 In the case of each it's set to the element for the current iteration of the value. 对于each情况,将其设置为值的当前迭代的元素。

The self trick works because it saves the this as it's bound in the function initRows and then uses that saved value in the iteration. self招的作品,因为它节省了this ,因为它在函数的约束initRows ,然后使用该迭代中保存的值。

initRows : function() {
    $A(this._elmnt.tBodies).each(function(body) {
        $A(body.rows).each((function(e, row) {
            e.rows.push(row);
            console.log(e);
        }).bindAsEventListener(this, row));
    });
}

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

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