javascriptdesign-patternserrata

Pro Javascript Design Patterns errata?


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

Solution

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