0

我有一个 javascript 对象,该对象具有一个属性,该属性在对象被实例化后分配了一个值。然后我想在对象的函数中使用该值。然而,该函数不是新分配的值,而是只看到属性的初始值(即 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)
4

2 回答 2

1

您可以使用设置器:

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

注意:现代 JavaScript 也有实际的 getter 和 setter,你可以用Object.defineProperty.

于 2013-05-20T21:37:38.120 回答
0

那是因为您的函数关闭了变量 test,而这正是您在函数中使用的。您根本没有使用该属性 Test

要使用该属性 Test(因为您在创建该属性时已将其指定为大写字母):

var getTest = function () {

    return this.Test;
    //     ^^^^^^
};

使用属性需要给出对象引用(this.在上面),并且属性名称有一个大写T而不是小写。


请注意,正如引用的那样,您的对象比它需要的要复杂得多。你可以这样写:

var _protocolData = {

    Test:    null,
    GetTest: function () {

        return this.Test;
    }
};
于 2013-05-20T21:36:07.250 回答