Short answer: no, not really. It is a prototype-based, object-based language but does not exhibit key characteristics of OOP languages, which I should delve into in another post.
It does have ways of using its prototype-based functionality to mimic OOP, and in ES6 you can declare class constructors with the 'class' keyword, but all this seems to be regarded by the developer community largely as, "syntactic sugar. " How js functions in its core has not changed.. but the new syntax does enhance the code's readability and streamlines its operation a bit.
There is still some confusion though because this syntax make sit seem like editing the properties of the class would propagate to its instances, but it does not. Only editing the property of the prototype the instance object is pointing to, would.
Here are some ways the class
syntax can be used to construct objects of the same 'class' (blueprint): [mdn]
// Declaration
class Rectangle {
constructor(height, width) {
this.height = height;
this.width = width;
}
// Getter
get area() {
return this.calcArea();
}
// Method
calcArea() {
return this.height * this.width;
}
}
}
// Expression; the class is anonymous but assigned to a variable
const Rectangle = class {
constructor(height, width) {
this.height = height;
this.width = width;
}
};
// Expression; the class has its own name
const Rectangle = class Rectangle2 {
constructor(height, width) {
this.height = height;
this.width = width;
}
};
const rect = new Rectangle(120, 380);
constructor
functionconstructor()
: a function that instantiates - as in, creates and initializes - an object based on the class new
keyword this
keyword: refers to the instance object itself. any changes to this
properties are changes just to that specific instance ES6 syntax obscures the prototype inheritance model... for better or worse. Below are excerpts from the Core Javascript book, which someone neatly organized into a table and examples here:
Class declarations have the same temporal dead zone restrictions as let or const and behave as if they are not hoisted. (mdh)
Unlike function declarations that are hoisted, this means it will throw a reference error if you try to invoke the class name and constructor function before it has been declared.
If you create an object using object literals, that object is a singleton, and changes made to that singular object affects that object across the entire script. Objects defined with a function constructor lets us create multiple instances of that object. Changes made to one instance object will not affect the others.
Especially if it includes this
.. it will not bind this
to the instantiated object itself, but instead inherits one from its parent scope (lexical scoping).
If you purposefully want this
to refer to its parent scope, it could also become handy.
To dig into more, later..
Object Literal vs. Constructor in Javascript