ES6 giới thiệu class — **cú pháp đường men (syntactic sugar)** cho prototype-based inheritance. Class bản chất là "special function".
Class Declaration
class Person {
constructor(name) { this.name = name; }
displayName() { console.log(this.name); }
}
Tương đương prototype (ES5)
let Person = function(name) { this.name = name; };
Person.prototype.displayName = function() { console.log(this.name); };
Class Expression
// Unnamed
let Person = class {
constructor(name) { this.name = name; }
displayName() { console.log(this.name); }
};
Tạo instance
let john = new Person("John");
john.displayName(); // John
Tài liệu sâu: ES6 Classes