javascript - 如何从 'each' 迭代器获取对象字段。 'this' 上下文错误

标签 javascript jquery this

我有原型(prototype)和名为 Parser 的“类”,如下所示:

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));

我无法将“表”移动到原型(prototype)中,因为在每个实例中我都应该有自己的字段

我试试这个:

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(...),因为它更合适。

例如

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(...) 的内容。

关于javascript - 如何从 'each' 迭代器获取对象字段。 'this' 上下文错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25665541/

相关文章:

javascript - VSCode JavaScript 自动完成将 "this"变成 "globalThis"

javascript - 在 JavaScript 的对象方法中使用 'this'

javascript - 如何构建/部署 Angular 2 项目到生产环境?

jquery - 如何等待变量不为空

javascript - 'this' 在下一个范围内未定义

javascript - 根据 id 对多个 div 使用相同的函数

javascript - jQuery 获取 "event invoking"元素

javascript - 使用文本框动态取消选中容器中的所有复选框

javascript - ngf-max-size $digest() 与 angular.js 中的 ng-file-upload 错误

javascript - Chrome.serial API - 通过串口读取正确的字节数