访问对象函数中Javascript属性的赋值

访问对象函数中Javascript属性的赋值,javascript,javascript-objects,Javascript,Javascript Objects,我有一个javascript对象,它有一个属性,该属性在对象实例化后被赋值。然后我想在对象的函数中使用这个值。但是,函数只看到属性的初始值(即null),而不是新指定的值 这是因为您的函数关闭变量test,这就是您在函数中使用的内容。您根本没有使用属性Test 要使用属性Test(因为您在创建属性时已将其大写): 使用属性需要提供对象引用(this.,在上面),并且属性名称的大小写为T,而不是小写 请注意,引用的对象比需要的复杂得多。你可以这样写: var _protocolData = {

我有一个javascript对象,它有一个属性,该属性在对象实例化后被赋值。然后我想在对象的函数中使用这个值。但是,函数只看到属性的初始值(即null),而不是新指定的值


这是因为您的函数关闭变量
test
,这就是您在函数中使用的内容。您根本没有使用属性
Test

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

使用属性需要提供对象引用(
this.
,在上面),并且属性名称的大小写为
T
,而不是小写


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

var _protocolData = {

    Test:    null,
    GetTest: function () {

        return this.Test;
    }
};
您可以使用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");

注意:现代JavaScript也有实际的getter和setter,您可以使用它们来创建

我熟悉javascript对象的文字语法,但是,我喜欢Revelaing模块模式提供的能够定义私有变量/函数的概念。使用“this”和您描述的属性名称确实是解决方案!!谢谢。Javascript的getter/Setters!?很好!:)这对我来说是新闻!!我会更仔细地研究它。谢谢你的指导!
var _protocolData = {

    Test:    null,
    GetTest: function () {

        return this.Test;
    }
};
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");