Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
78
rated 0 times [  82] [ 4]  / answers: 1 / hits: 15534  / 15 Years ago, mon, may 25, 2009, 12:00:00

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.


More From » object

 Answers
7

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.


[#99462] Wednesday, May 20, 2009, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
chase

Total Points: 78
Total Questions: 106
Total Answers: 93

Location: Comoros
Member since Tue, Mar 14, 2023
1 Year ago
chase questions
Thu, Mar 31, 22, 00:00, 2 Years ago
Thu, Jul 1, 21, 00:00, 3 Years ago
Sat, Dec 12, 20, 00:00, 4 Years ago
Mon, Sep 14, 20, 00:00, 4 Years ago
;