sorenymous
sorenymous

Reputation: 92

ES6 const for creating object prototypes in JavaScript; is this a pattern?

I often see const being used to create a base object.

  1. Is this a pattern?
  2. If yes, what are the advantages?

Example from here:

const food = {
    init: function(type) {
        this.type = type;
    }
}

const waffle = Object.create(food);
waffle.init('waffle');
console.log(waffle.type);

Upvotes: 4

Views: 857

Answers (1)

ykaragol
ykaragol

Reputation: 6221

const declares a readonly reference. You cannot change the value if declared with const. See documantation from MDN:

The const declaration creates a read-only reference to a value. It does not mean the value it holds is immutable, just that the variable identifier cannot be reassigned.

For example:

const x = {a:2};//declaration. 
x={b:3};//This statement throws an exception
x.c=4;//This is ok!

So, const provides these:

  1. The initial defined object cannot be reassigned.(readonly)
  2. The properties of the initial object can be reassigned.
  3. New properties can be added to the initial object.

These are perfectly suitable for class definitions!

On the other hand, there are two alternatives to declare a value: var and let. Both cannot provide read-only referencing. Also var doesn't provide a block-scope declaration. Of course you can use either var or let. This is your choice and your usage.

Also in ES6, you can define classes like that (resource from MDN):

class Polygon {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
}

And Babel translates it like this (by using var):

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var Polygon = function Polygon(height, width) {
  _classCallCheck(this, Polygon);

  this.height = height;
  this.width = width;
};

Upvotes: 5

Related Questions