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.
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 .
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With