為什麼要使用ES6類?

banq發表於2019-01-04

選擇使用類的一些原因:
  • 語法更簡單,更不容易出錯。
  • 使用新的語法比舊語法在實現繼承方面容易得多。
  • class保護您免受無法使用new建構函式的常見錯誤(如果建構函式不是建構函式this的有效物件,則使建構函式丟擲異常)。
  • 呼叫父原型的方法版本要簡單得多,如super.method(),而不是舊語法(ParentConstructor.prototype.method.call(this)或Object.getPrototypeOf(Object.getPrototypeOf(this)).method.call(this))

看看ES5:

// **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() {
    // ...
};


而看看ES6的類:

// ***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() {
        // ...
    }
}


Source: stackoverflow.com

 

相關文章