Cod*_*lad 12 javascript constants object
在javascript中,我可以声明对象的属性是常量吗?
这是一个示例对象:
var XU = {
Cc: Components.classes
};
Run Code Online (Sandbox Code Playgroud)
要么
function aXU()
{
this.Cc = Components.classes;
}
var XU = new aXU();
Run Code Online (Sandbox Code Playgroud)
只是把"const"放在它前面,不起作用.
我知道,我可以声明具有相同名称(这也将是样的常数)的函数,但是我正在寻找一个更简单,更可读的方式.
浏览器兼容性并不重要.它只需要在Mozilla平台上工作,就像Xulrunner项目一样.
非常感谢!
干杯.
Mat*_*ley 12
由于您只需要它在Mozilla平台上工作,因此您可以定义一个没有相应setter的getter.对于每个示例,最好的方法是不同的.
var XU = {
get Cc() { return Components.classes; }
};
Run Code Online (Sandbox Code Playgroud)
在第二个例子中,您可以使用该__defineGetter__方法将其添加到构造函数中的任何一个aXU.prototype或this内部.哪种方式更好取决于对象的每个实例的值是否不同.
编辑:为了帮助解决可读性问题,您可以编写一个defineConstant隐藏丑陋的函数.
function defineConstant(obj, name, value) {
obj.__defineGetter__(name, function() { return value; });
}
Run Code Online (Sandbox Code Playgroud)
此外,如果您想在尝试分配错误时抛出错误,则可以定义一个只抛出Error对象的setter:
function defineConstant(obj, name, value) {
obj.__defineGetter__(name, function() { return value; });
obj.__defineSetter__(name, function() {
throw new Error(name + " is a constant");
});
}
Run Code Online (Sandbox Code Playgroud)
function aXU() {
}
defineConstant(aXU.prototype, "Cc", Components.classes);
Run Code Online (Sandbox Code Playgroud)
function aXU() {
// Cc_value could be different for each instance
var Cc_value = return Components.classes;
defineConstant(this, "Cc", Cc_value);
}
Run Code Online (Sandbox Code Playgroud)
有关更多详细信息,请阅读Mozilla开发人员中心文档.
更新:这有效!
const FIXED_VALUE = 37;
FIXED_VALUE = 43;
alert(FIXED_VALUE);//alerts "37"
Run Code Online (Sandbox Code Playgroud)
从技术上讲,我认为答案是否定的(直到const使它成为狂野的).你可以提供包装等等,但是当它归结为它时,你可以随时重新定义/重置变量值.
我认为你最接近的是在"阶级"上定义一个"常数".
// Create the class
function TheClass(){
}
// Create the class constant
TheClass.THE_CONSTANT = 42;
// Create a function for TheClass to alert the constant
TheClass.prototype.alertConstant = function(){
// You can’t access it using this.THE_CONSTANT;
alert(TheClass.THE_CONSTANT);
}
// Alert the class constant from outside
alert(TheClass.THE_CONSTANT);
// Alert the class constant from inside
var theObject = new TheClass();
theObject.alertConstant();
Run Code Online (Sandbox Code Playgroud)
但是,"class" TheClass本身可以在以后重新定义
| 归档时间: |
|
| 查看次数: |
14287 次 |
| 最近记录: |