Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 913
CJe Avatar asked Nov 13 '12 05:11

CJe


People also ask

Why is my JavaScript variable undefined?

A variable that has not been assigned a value is of type undefined . A method or statement also returns undefined if the variable that is being evaluated does not have an assigned value. A function returns undefined if a value was not returned .

Can JavaScript variables start with _?

Naming Conventions for JavaScript VariablesA variable name must start with a letter, underscore ( _ ), or dollar sign ( $ ). A variable name cannot start with a number. A variable name can only contain alpha-numeric characters ( A-z , 0-9 ) and underscores. A variable name cannot contain spaces.

What does _ do in JavaScript?

The dollar sign ($) and the underscore (_) characters are JavaScript identifiers, which just means that they identify an object in the same way a name would. The objects they identify include things such as variables, functions, properties, events, and objects.


2 Answers

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);
    }
    
like image 86
DCoder Avatar answered Oct 14 '22 09:10

DCoder


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

like image 41
Andrey Kuzmin Avatar answered Oct 14 '22 10:10

Andrey Kuzmin