Sự khác biệt giữa hàm tạo của ES6 class và hàm tạo của ES5 function là gì?

{{FormatNumbertoThousand(model.total_like)}} lượt thích
363 lượt xem
Javascript middle

Trước tiên, hãy xem 2 ví dụ dưới đây:

// ES5 Function Constructor
function Person(name) {
   this.name = name;
}

// ES6 Class
class Person {
   constructor(name) {
      this.name = name;
   }
}

Đối với các hàm tạo đơn giản, chúng trông khá giống nhau.

Sự khác biệt chính trong hàm tạo là khi sử dụng kế thừa. Nếu chúng ta muốn tạo một lớp Student là lớp con của lớp Person và thêm 1 trường studentId, đây là những gì chúng ta phải làm ngoài những điều trên.

// ES5 Function Constructor
function Student(name, studentId) {
   // Call constructor of superclass to initialize superclass-derived members.
   Person.call(this, name);
   // Initialize subclass's own members.
   this.studentId = studentId;
} 

Student.prototype = Object.create(Person.prototype);
Student.prototype.constructor = Student;

// ES6 Class
class Student extends Person {
   constructor(name, studentId) {
      super(name);
      this.studentId = studentId;
   }
}

Sử dụng kế thừa trong ES5 dài dòng hơn nhiều và phiên bản ES6 dễ hiểu và dễ nhớ hơn.

{{login.error}}