ES5继承和ES6继承的区别

ES5继承

这里使用的是最常用的组合继承,要了解其他的继承方式可以ES5继承方式

function Person (name,gender){
    this.name = name;
    this.gender = gender;
}
Person.prototype.getName = function() {
    console.log(this.name);
}
function Student (name,gender,grade) {
    Person.call(this,name,gender);
    this.grade = grade;
}
Student.prototype = new Person();
Student.prototype.constructor = Student;
const student = new Student('Jason','男','大三');
student.getName();
console.log(student);
// Jason
// Student {name: "Jason", gender: "男", grade: "大三"}

ES6继承

使用extend关键字

class Person {
    constructor(name,gender){ //属性写这里
       this.name = name;
       this.gender = gender
    }
    //方法写后面
    getName() {
       console.log(this.name);
    }
}
class Student extends Person{
   constructor(name,gender,grade){
       super(name,gender);
       this.grade=grade;
   }
}
const student = new Student('Jason','男','大三');
student.getName();
console.log(student);
// Jason
// Student {name: "Jason", gender: "男", grade: "大三"}

你可能感兴趣的:(前端)