Javascript:常量属性 [英] Javascript: constant properties

查看:94
本文介绍了Javascript:常量属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在javascript中,我可以声明对象的属性是常量吗?

In javascript, can I declare properties of an object to be constant?

这是一个示例对象:

   var XU = {
      Cc: Components.classes
   };

   function aXU()
   {
      this.Cc = Components.classes;
   }

   var XU = new aXU();

只是将const放在它前面,不起作用。

just putting "const" in front of it, doesn't work.

我知道,我可以声明一个具有相同名称的函数(这也是一种常量),但我正在寻找一种更简单,更易读的方法。

I know, that i could declare a function with the same name (which would be also kind of constant), but I am looking for a simpler and more readable way.

浏览器兼容性并不重要。它只需要在Mozilla平台上工作,就像Xulrunner项目一样。

Browser-compatibility is not important. It just has to work on the Mozilla platform, as it is for a Xulrunner project.

非常感谢你!

干杯。

推荐答案

由于您只需要它在Mozilla平台上工作,您可以定义一个没有相应的getter二传手。对于每个示例,最好的方法是不同的。

Since you only need it to work on the Mozilla platform, you can define a getter with no corresponding setter. The best way to do it is different for each of your examples.

var XU = {
    get Cc() { return Components.classes; }
};

在你的第二个例子中,你可以使用 __ defineGetter __ 在构造函数中将它添加到 aXU.prototype 或这个的方法。哪种方式更好取决于对象的每个实例的值是否不同。

In your second exampe, you can use the __defineGetter__ method to add it to either aXU.prototype or to this inside the constructor. Which way is better depends on whether the value is different for each instance of the object.

编辑:为了帮助解决可读性问题,可以写一个像 defineConstant 这样的函数来隐藏丑陋。

To help with the readability problem, you could write a function like defineConstant to hide the uglyness.

function defineConstant(obj, name, value) {
    obj.__defineGetter__(name, function() { return value; });
}

另外,如果你想在尝试分配错误时抛出错误,你可以定义一个只抛出一个Error对象的setter:

Also, if you want to throw an error if you try to assign to it, you can define a setter that just throws an Error object:

function defineConstant(obj, name, value) {
    obj.__defineGetter__(name, function() { return value; });
    obj.__defineSetter__(name, function() {
        throw new Error(name + " is a constant");
    });
}



如果所有实例具有相同的值:



If all the instances have the same value:

function aXU() {
}

defineConstant(aXU.prototype, "Cc", Components.classes);



或者,如果值取决于对象:



or, if the value depends on the object:

function aXU() {
    // Cc_value could be different for each instance
    var Cc_value = return Components.classes;

    defineConstant(this, "Cc", Cc_value);
}

有关详情,请阅读 Mozilla开发人员中心文档

这篇关于Javascript:常量属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆