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:
- The initial defined object cannot be reassigned.(readonly)
- The properties of the initial object can be reassigned.
- 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;
};