Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
68
rated 0 times [  73] [ 5]  / answers: 1 / hits: 16596  / 12 Years ago, tue, november 13, 2012, 12:00:00

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.


More From » variables

 Answers
4

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


[#82028] Sunday, November 11, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
allans

Total Points: 336
Total Questions: 120
Total Answers: 119

Location: Peru
Member since Mon, Jun 6, 2022
2 Years ago
allans questions
;