Accessing the assigned value of a Javascript property in an object function

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

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)

Answers

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

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/16658776/accessing-the-assigned-value-of-a-javascript-property-in-an-object-function

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils