Ronaldo Vitto Lewerissa

Software engineering learning documentation.

JavaScript Constructor Pattern

There are 3 ways to create an object in JavaScript:

let object1 = {};

let object2 = Object.create(Object.prototype);

let object3 = new Object({key: val, ... });  

The first option is an object literal where basically is a key-value pair.

The second lets you specify the prototype for the object you're trying to create. You'll able to see it by accessing object2.__proto__. You'll need to specify the prototype or otherwise it will throws.

Remember that every object inherits Object.prototype by default.

So for instance, object1.__proto__ will be equivalent to Object.prototype without be obliged to specify the prototype by yourself. But for the second option, you'll be needing to sepcify Object.prototype by yourself.

The following achieve the same result as the third option:

Object({key: val, ... });  
Accessing and Mutating Props

You'll mainly use either dot notation . or a bracket notation [].

For setting/assigning a new property, you can also use Object.defineProperty(), by the following syntax:

Object.defineProperty(obj, prop, descriptor)  

There are two type of descriptor, you can only choose either of these, otherwise it will throws.

  • data descriptor
  • accessor descriptor

Both have the following key:

  • configurable: are the descriptor mutable?
  • enumerable: will the property shows up during enumeration (for ... in and Object.keys).

For data descriptor:

  • value: well, the value for the property.
  • writable: is the property mutable?

Ex:

Object.defineProperty(obj, 'awesomeKey', {  
  enumerable: false,
  configurable: false,
  writable: false,
  value: 'Some random awesome value'
});

There are defaults for every of these descriptor keys, so you don't have to explicitly specify for each.

But if you don't, there is a possibility where the options are inherited from the prototype chain. I'm not really sure about this, though...

For accessor:

  • get
  • set

Both get and set are function that will be executed when you either assign or access the corresponding key. For instance:

let Cat = {};  
Object.defineProperty(Cat, 'age', {  
    get: function() {
      return this.age || 10;
    },
    set: function(value) {
      this.age = value;
    }
  });

console.log(Cat.age); // returns 10  
Cat.age = 12;  
console.log(Cat.age); //returns 12  

Written by Ronaldo Vitto Lewerissa

Read more posts by this author.