繁体   English   中英

如何从“每个”迭代器获取对象字段。 错误的“此”上下文

[英]How to get object field from 'each' iterator. Wrong 'this' context

我有这样的原型和名为“解析器”的“类”,如下所示:

function Parser(year){
  this.table = [];
}

Parser.prototype = {
  _months: [0, 3, 6, 12, 15, 18, 27, 30, 33, 39, 42, 45], 

  getCalendar: function(year){
    $.ajax({
      url: "http://www.domain.com/" + year,
      success: $.proxy(function(data, status, xhr) {
        $(Parser.prototype._monthes).each(function (i, v){
          // problem in this line: how I can get field 'tabel' from my object of Parser class
          this.table.push(parseInt($(".wstd tr td div.wstd_type2", data)[v].innerHTML, 10));
        });
}, this)});

//这行中的问题:如何从Parser类的对象中获取字段“ tabel”

this.table.push(parseInt($(".wstd tr td div.wstd_type2", data)[v].innerHTML, 10));

我不能将“表”移入原型,因为在每种情况下我都应该拥有自己的字段

我尝试这样:

var _table = []
$(Parser.prototype._monthes).each(function (i, v){
  _table.push(parseInt($(".wstd tr td div.wstd_type2", data)[v].innerHTML, 10));
});
this.table = _table;

可以,但是很脏。 还有其他方法吗?

摆脱所有这些$.proxy疯狂,只使用闭包即可。 还要注意,我将$(...).each更改$(...).each $.each(...)因为它更合适。

例如

getCalendar: function(year) {
    var that = this;

    $.ajax({
        url: "http://www.domain.com/" + year,
        success: function(data, status, xhr) {
            $.each(that._monthes, function(i, v) {
                that.tabel.push(parseInt($(".wstd tr td div.wstd_type2", data)[v].innerHTML, 10));
            });
        }
    });
}

另一个要注意的是,除非函数名称描述了数据检索操作,否则它不会产生副作用。 它使您的代码不灵活且难以理解。 getCalendar没有任何内容表明它可能会改变对象的状态。

您可能应该有类似this.getCalendar().then(...)

您可以一直使用$.proxy()

getCalendar: function(year){
    $.ajax({
      url: "http://www.domain.com/" + year,
      success: $.proxy(function(data, status, xhr) {
        $(Parser.prototype._monthes).each($.proxy(function (i, v){
          // problem in this line: how I can get field 'tabel' from my object of Parser class
          this.tabel.push(parseInt($(".wstd tr td div.wstd_type2", data)[v].innerHTML, 10));
        }, this); 
      }, this)});
   })
}

另一个选择是使用Function.prototype.bind() 无论哪种情况,我都建议将您的函数分解掉,以免迷失在所有大括号和括号中。 这是您可以使用bind() (而且我已经纠正了“表”和“月”的拼写):

Parser.prototype = {
  _months: [0, 3, 6, 12, 15, 18, 27, 30, 33, 39, 42, 45], 

  _handleCalendarSuccess: function (data, status, xhr) {
      var values = $(".wstd tr td div.wstd_type2", data);

      $.each(this._months, function (i, v) {
          this.table.push(parseInt(values[v].innerHTML, 10));
      }.bind(this));
  },

  getCalendar: function(year){
    $.ajax({
      url: "http://www.domain.com/" + year,
      success: this._handleCalendarSuccess.bind(this)
    });
  }
};

暂无
暂无

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

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