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: "大三"}
本文详细对比了ES5中的组合继承方法与ES6中使用class和extend关键字实现的继承方式。通过具体示例,展示了两种继承方式的具体实现过程及特点。
2480

被折叠的 条评论
为什么被折叠?



