Can anyone confirm that these samples from Chapter 3 of Pro Javascript Design Patterns are flawed and, if so, how fundamentally - are they more than a typo or two away from producing the intended goal of 'class' constants in JavaScript? Thanks.
var Class = (function() {
// Constants (created as private static attributes).
var UPPER_BOUND = 100;
// Privileged static method.
this.getUPPER_BOUND() {//sic
return UPPER_BOUND;
}
...
// Return the constructor.
return function(constructorArgument) {
...
}
})();
/* Usage. */
Class.getUPPER_BOUND();
/* Grouping constants together. */
var Class = (function() {
// Private static attributes.
var constants = {
UPPER_BOUND: 100,
LOWER_BOUND: -100
}
// Privileged static method.
this.getConstant(name) {//sic
return constants[name];
}
...
// Return the constructor.
return function(constructorArgument) {
...
}
})();
/* Usage. */
Class.getConstant('UPPER_BOUND');
I think, this is wrong. As mentioned previously, "this" refers to the window object and the code also has a syntax error. The following code should accomplish the required goal:
var Class = (function () {
// Private static attributes.
var constants = {
UPPER_BOUND: 100,
LOWER_BOUND: -100
};
var sc = function (constructorArgument) {
};
// Privileged static method.
sc.getConstant = function (name) {
return constants[name];
};
// Return the constructor.
return sc;
})();
alert(Class.getConstant('UPPER_BOUND'));
The code can be trivially fixed as
var Class = {
UPPER_BOUND: 100
};
The rest of the code is over engineered or plain wrong and should be ignored.
If you care about being read only then set the writable flag to false (note the default is false).
var Class = {};
Object.defineProperty(Class, "UPPER_BOUND", {
value: 100,
enumerable: true,
configurable: true
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With