Why is my variable undefined inside the Underscore.js each function?

前端 未结 4 643
無奈伤痛
無奈伤痛 2021-02-05 08:32

Here is my code:

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

TextClass.prototype = {
    SetTexts: function (texts) {
        for (var i = 0; i < te         


        
4条回答
  •  南方客
    南方客 (楼主)
    2021-02-05 08:35

    In JavaScript, the function context, known as this, works rather differently.

    You can solve this in two ways:

    1. Use a temporary variable to store the context:

      SetTexts: function (texts) {
        var that = this;
        _.each(texts, function (text) {
          that._textArr[text.Key] = text.Value;
        });
      }
      
    2. Use the third parameter to _.each() to pass the context:

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

提交回复
热议问题