這裏是我的代碼:爲什麼我的變量在Underscore.js中的每個函數內都未定義?
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;
});
但_textArr是不確定的,當我進入循環。
因爲回調裏面的this和外面的不一樣。使用第三個參數'each'來傳遞你想要的回調內容。 – DCoder