ES6类和ES5函数构造函数有什么区别?


我们先来看看每个例子:

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

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

对于简单的构造函数,它们看起来非常相似。
使用继承时,构造函数的主要区别在于。如果我们想创建一个Student子类Person并添加studentId字段的类,那么除了上述内容之外,我们还必须这样做:

// 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;
  }
}

在ES5中使用继承更加冗长,ES6版本更易于理解和记忆。