内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用
这是我的代码:
TextClass = function () {
this._textArr = {};
};
TextClass.prototype = {
SetTexts: function (texts) {
for (var i = 0; i < texts.length; i++) {
this._textArr[texts[i].Key] = texts[i].Value;
}
},
GetText: function (key) {
var value = this._textArr[key];
return String.IsNullOrEmpty(value) ? 'N/A' : value;
}
};
我正在使用Underscore.js库,并想要像这样定义我的SetTexts函数:
_.each(texts, function (text) {
this._textArr[text.Key] = text.Value;
});
在JavaScript中,
你可以用两种方法解决这个问题:
SetTexts: function (texts) { var that = this; _.each(texts, function (text) { that._textArr[text.Key] = text.Value; }); }
_.each()
来传递上下文:
SetTexts: function (texts) { _.each(texts, function (text) { this._textArr[text.Key] = text.Value; }, this); }