19

这是我的代码:

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 是未定义的。

4

4 回答 4

38

在 JavaScript 中,函数上下文(称为)的this工作方式完全不同

您可以通过两种方式解决此问题:

  1. 使用临时变量来存储上下文:

    SetTexts: function (texts) {
      var that = this;
      _.each(texts, function (text) {
        that._textArr[text.Key] = text.Value;
      });
    }
    
  2. 使用第三个参数来_.each()传递上下文:

    SetTexts: function (texts) {
      _.each(texts, function (text) {
        this._textArr[text.Key] = text.Value;
      }, this);
    }
    
于 2012-11-13T06:13:40.560 回答
6

您必须像这样传递调用this的上下文:_.each

_.each(texts, function (text) {
    this._textArr[text.Key] = text.Value;
}, this);

请参阅http://underscorejs.org/#each的文档

于 2012-11-13T06:13:56.760 回答
1

this在 javascript 中的工作方式与您期望的不同。阅读这篇文章: http ://www.digital-web.com/articles/scope_in_javascript/

简洁版本:

this每次调用函数时值都会发生变化。修复,设置另一个变量等于this并引用它

TextClass = function () {
    this._textArr = {};
};

TextClass.prototype = {
    SetTexts: function (texts) {
        var that = this;
        for (var i = 0; i < texts.length; i++) {
            that._textArr[texts[i].Key] = texts[i].Value;
        }
    },
    GetText: function (key) {
        var value = this._textArr[key];
        return String.IsNullOrEmpty(value) ? 'N/A' : value;
    }
};
于 2012-11-13T06:09:28.270 回答
0

请注意,您还可以传递“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);
于 2014-05-23T16:10:05.743 回答