保持变量私有并通过JS中的通用函数访问它们

时间:2013-11-21 10:46:26

标签: javascript json

我想创建一个包含所有常量属性的对象,并且这些属性不能通过外部世界进行更改,

例如:

var Constants = (function(){
    this.server_port = 8888;
    this.server_name = '127.0.0.1';

    return ({
            getConstantValue : function(constantName){
                /*
                  Now this will return the property as per the name of the 
                  constant passed
                */
            }
    });
}());

所以,现在如果有人说

Constants.getConstantValue('server_port');//will return 8888;
Constants.getConstantValue('server_name');//will return 127.0.0.1;

如何实现这一点,记住我不想将这些属性暴露给外界,请稍微阐明一下。 在此先感谢。

3 个答案:

答案 0 :(得分:4)

Closures!稍加重构:

var constants = (function() {
    var constList = {
        server_port : 8888,
        server_name : '127.0.0.1'
    };
    return ({
        getConstantValue : function(constantName) {
            return constList[constantName];
        }
    });
}());

答案 1 :(得分:3)

更自然的方式是使用真实属性,例如:

function Const(obj) {
    var o = {};
    Object.keys(obj).forEach(function(k) {
        o.__defineGetter__(k, function() { return obj[k] })
    });
    return o;
}

function Const(obj) {
    var o = {};
    Object.keys(obj).forEach(function(k) {
        o[k] = { writable: false, value: obj[k] }
    });
    return Object.create({}, o);
}

然后

config = new Const({
    'server_port': 8888,
    'server_name': '127.0.0.1'
})


console.log(config.server_name) // 127.0.0.1
config.server_name = 'blah'
console.log(config.server_name) // still 127.0.0.1

答案 2 :(得分:2)

试试这个(demo):

var Constants = (function(){
    var server_port = 8888;
    var server_name = '127.0.0.1';

    return ({
            getConstantValue : function(constantName){
                if(constantName == "server_port")
                {
                    return server_port;
                }
            }
    });
}());