Reputation: 92
I often see const
being used to create a base object.
const food = {
init: function(type) {
this.type = type;
}
}
const waffle = Object.create(food);
waffle.init('waffle');
console.log(waffle.type);
Upvotes: 4
Views: 857
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:
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