我想制作一个包含所有常量属性的对象,并且这些属性不能通过外界改变,
例如:
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/