Reputation: 2294
I have a javascript object that has a property which is assigned a value after the object has been instantiated. I then want to use the value in a function of the object. Instead of the newly assigned value however, the function is only seeing the initial value of the property (i.e. null)
var _protocolData = new function () {
var test = null;
var getTest = function () {
return test;
};
return {
Test: test,
GetTest: getTest
};
};
//
// assign the new property value
_protocolData.Test = "New Value";
//
// I expect the dialog box to be populated with "New Value".
alert(_protocolData.GetTest()); // alert box is empty (null)
Upvotes: 0
Views: 117
Reputation: 1074148
That's because your function closes over the variable test
and that's what you're using in your function. You're not using the property Test
at all.
To use the property Test
(because you've given it the capital letter when making the property):
var getTest = function () {
return this.Test;
// ^^^^^^
};
Using the property requires giving the object reference (this.
in the above), and the property name has a capital T
rather than a lower-case one.
Note that your object, as quoted, is much more complicated than it needs to be. You can write it like this:
var _protocolData = {
Test: null,
GetTest: function () {
return this.Test;
}
};
Upvotes: 0
Reputation: 71908
You can use a setter:
var _protocolData = new function () {
var test = null;
var getTest = function () {
return test;
};
var setTest = function(t) {
test = t;
}
return {
Test: test,
GetTest: getTest,
SetTest: setTest
};
};
// assign the new property value
_protocolData.SetTest("New Value");
Note: modern JavaScript also have actual getters and setters, which you could create with Object.defineProperty
.
Upvotes: 1