javascript - 保持变量私有(private)并通过 JS 中的通用函数访问它们

标签 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;

如何实现,请记住我不想将这些属性暴露给外界,请说明一下。 提前致谢。

最佳答案

Closures!稍作重构:

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

关于javascript - 保持变量私有(private)并通过 JS 中的通用函数访问它们,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20118776/

相关文章:

JavaScript:将未定义处理为参数 - 这些解决方案是否相同?

c++ - cURL 处理大型 JSON 响应

javascript - 使用 JavaScript/jQuery 处理复杂的 html 元素

javascript - Aurelia-repeat.for json

jquery - CORS header 'Access-Control-Allow-Origin' 丢失

javascript - 复选框 - 仅选中一个复选框即可选中多个复选框

javascript - Leaflet实时GeoJSON动态标记颜色变化

javascript - 使用 jquery 获取下拉列表的 json 数据不起作用

javascript - 数组包含吗?

javascript子函数将返回值传递给父函数返回值