选择使用类的一些原因:
- 语法更简单,更不容易出错。
- 使用新的语法比旧语法在实现继承方面容易得多。
- 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