JavaScript classes, introduced in ECMAScript 2015, are primarily syntactical sugar over JavaScript's existing prototype-based inheritance. The class syntax does not introduce a new object-oriented inheritance model to JavaScript.
In fact at its core js borrows (a lot) from the object-oriented model from the language self, which is a biologically inspired one?
And classes in JS is just a syntactic sugar for the inner prototype based model.
Defining classes
Classes are in fact "special functions", and just as you can define function expressions and function declarations, the class syntax has two components: class expressions and class declarations.
Class declarations
class Rectangle {
constructor(height, width) {
this.height = height;
this.width = width;
}
}
An important difference between function declarations and class declarations is that function declarations are hoisted and class declarations are not. You first need to declare your class and then access it, otherwise code like the following will throw a ReferenceError:
const p = new Rectangle(); // ReferenceError
class Rectangle {}
Class expressions:
// unnamed
let Rectangle = class {
constructor(height, width) {
this.height = height;
this.width = width;
}
};
console.log(Rectangle.name);
// output: "Rectangle"
// named
let Rectangle = class Rectangle2 {
constructor(height, width) {
this.height = height;
this.width = width;
}
};
console.log(Rectangle.name);
// output: "Rectangle2"
Ref: 1. MDN
No comments:
Post a Comment