为什么我的变量在Underscore.js中的每个函数都未定义?

CJe*_*CJe 19 javascript variables 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;
    }
};
Run Code Online (Sandbox Code Playgroud)

我正在使用Underscore.js库,并希望像这样定义我的SetTexts函数:

_.each(texts, function (text) {
    this._textArr[text.Key] = text.Value;
});
Run Code Online (Sandbox Code Playgroud)

但是当我进入循环时,_textArr是未定义的.

DCo*_*der 37

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

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

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

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

    SetTexts: function (texts) {
      _.each(texts, function (text) {
        this._textArr[text.Key] = text.Value;
      }, this);
    }
    
    Run Code Online (Sandbox Code Playgroud)


And*_*min 6

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

_.each(texts, function (text) {
    this._textArr[text.Key] = text.Value;
}, this);
Run Code Online (Sandbox Code Playgroud)

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