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

Here is my code:

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;
    }
};

I'm using the Underscore.js library and would like to define my SetTexts function like this:

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

but _textArr is undefined when I get into the loop.


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

You can solve this in two ways:

  • Use a temporary variable to store the context:

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

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

  • You have to pass this as context for _.each call like this:

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

    See the docs for http://underscorejs.org/#each


    this in javascript does not work the same way as you would expect. read this article: http://www.digital-web.com/articles/scope_in_javascript/

    short version:

    the value of this changes every time you call a function. to fix, set another variable equal to this and reference that instead

    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;
        }
    };
    
    链接地址: http://www.djcxy.com/p/94906.html

    上一篇: 严格禁止在node.js中使用这个

    下一篇: 为什么我的变量undefined在Underscore.js中的每个函数中?