下面是我的代码:
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是未定义的。
发布于 2012-11-13 14:13:57
您必须将this
作为_.each
调用的上下文进行传递,如下所示:
_.each(texts, function (text) {
this._textArr[text.Key] = text.Value;
}, this);
发布于 2014-05-24 00:10:06
请注意,您还可以传递"this“以外的其他内容。例如,我这样做:
var layerGroupMasterData = [[0],[1,2,3],[4,5],[6,7,8,9],[10]];
_.each(layerGroupMasterData,function(layerGroup,groupNum){
_.each(layerGroup, function (layer, i) {
doSomethingThatComparesOneThingWithTheOverallGroup(layerGroupMasterData,layer);
},layerGroups);
},layerGroupMasterData);
https://stackoverflow.com/questions/13356203
复制相似问题