JavaScript:常量属性

发布于 2024-07-21 05:35:01 字数 439 浏览 7 评论 0原文

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

这是一个示例对象:

   var XU = {
      Cc: Components.classes
   };

或者

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

   var XU = new aXU();

只是将“const”放在它前面,是行不通的。

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

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

万分感谢!

干杯。

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

Here is an example object:

   var XU = {
      Cc: Components.classes
   };

or

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

   var XU = new aXU();

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.

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

Thank you a lot!

Cheers.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

昔日梦未散 2024-07-28 05:35:01

由于您只需要它在 Mozilla 平台上工作,因此您可以定义一个 getter,而不需要相应的 setter。 每个示例的最佳方法都不同。

在对象字面量中,有一个特殊的语法:

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

在第二个示例中,您可以使用 __defineGetter__ 方法将其添加到 aXU.prototype>this 在构造函数中。 哪种方式更好取决于对象的每个实例的值是否不同。

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

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

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

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

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

function aXU() {
}

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

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

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

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

了解更多有关详细信息,您可以阅读 Mozilla 开发者中心文档

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.

In an object literal, there is a special syntax for it:

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

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.

Edit: 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; });
}

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);
}

For more details, you can read the Mozilla Developer Center documentation.

顾忌 2024-07-28 05:35:01

更新:这有效!

const FIXED_VALUE = 37;
FIXED_VALUE = 43;
alert(FIXED_VALUE);//alerts "37"

从技术上讲,我认为答案是否定的(直到 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();

然而,“类”TheClass本身可以在以后重新定义

UPDATE: This works!

const FIXED_VALUE = 37;
FIXED_VALUE = 43;
alert(FIXED_VALUE);//alerts "37"

Technically I think the answer is no (Until const makes it into the wild). You can provide wrappers and such, but when it all boils down to it, you can redefine/reset the variable value at any time.

The closest I think you'll get is defining a "constant" on a "class".

// 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();

However, the "class" TheClass itself can be redefined later on

不如归去 2024-07-28 05:35:01

如果您使用的是 Javascript 1.5(例如 XUL),则可以使用 const 关键字而不是 var 来声明常量。

问题是它不能是对象的属性。 您可以尝试通过在函数内命名它来限制其范围。

(function(){ 

const XUL_CC = Components.classes;

// Use the constant here

})()

If you are using Javascript 1.5 (in XUL for example), you can use the const keyword instead of var to declare a constant.

The problem is that it cannot be a property of an object. You can try to limit its scope by namespacing it inside a function.

(function(){ 

const XUL_CC = Components.classes;

// Use the constant here

})()
作死小能手 2024-07-28 05:35:01

要定义常量属性,您可以在 DefineProperty 方法中将 writable 属性设置为 false,如下所示:

代码片段:

var XU = {};

Object.defineProperty(XU, 'Cc', {
    value: 5,
    writable: false
});

XU.Cc = 345;

console.log(XU.Cc);

结果:

5           # The value hasn't changed

To define a constant property, you could set the writable attribute to false in the defineProperty method as shown below:

Code snippet:

var XU = {};

Object.defineProperty(XU, 'Cc', {
    value: 5,
    writable: false
});

XU.Cc = 345;

console.log(XU.Cc);

Result:

5           # The value hasn't changed
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文