我有原型(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/