Tại sao chúng ta nên sử dụng ES6 classes?

{{FormatNumbertoThousand(model.total_like)}} lượt thích
275 lượt xem
Javascript middle
  • Cú pháp đơn giản và ít lỗi hơn.
  • Việc thiết lập cấu trúc phân cấp kế thừa bằng cú pháp mới dễ dàng hơn nhiều (và một lần nữa, ít bị lỗi hơn).
  • class bảo vệ bạn khỏi lỗi phổ biến là không thể sử dụng new với hàm tạo (bằng cách hàm tạo thảy ra một exception nếu đây không phải là object hợp lệ cho hàm tạo).
  • Việc gọi phiên bản nguyên mẫu gốc của một method đơn giản hơn nhiều so với cú pháp cũ (super.method () thay vì ParentConstructor.prototype.method.call (this) hoặc Object.getPrototypeOf (Object.getPrototypeOf (this)). method.call (this)).

Xem xét đoạn code dưới đây:

// **ES5**
var Person = function(first, last) {
   if (!(this instanceof Person)) {
      throw new Error("Person is a constructor function, use new with it");
   }
   this.first = first;
   this.last = last;
};

Person.prototype.personMethod = function() {
   return "Result from personMethod: this.first = " + this.first + ", this.last = " + 
   this.last;
};

var Employee = function(first, last, position) {
   if (!(this instanceof Employee)) {
      throw new Error("Employee is a constructor function, use new with it");
   }
   Person.call(this, first, last);
   this.position = position;
};

Employee.prototype = Object.create(Person.prototype);
Employee.prototype.constructor = Employee;
Employee.prototype.personMethod = function() {
   var result = Person.prototype.personMethod.call(this);
   return result + ", this.position = " + this.position;
};
Employee.prototype.employeeMethod = function() {
// ...
};

Và tương tự như trên:

// ***ES2015+**
class Person {
   constructor(first, last) {
      this.first = first;
      this.last = last;
   }
   personMethod() {
   // ...
   }
} 

class Employee extends Person {
   constructor(first, last, position) {
      super(first, last);
      this.position = position;
   }
   employeeMethod() {
      // ...
   }
}
{{login.error}}