回顾 ES5 的继承
<script>
// ◆构造函数
function Person(name, age) {
this.name = name
this.age = age
};
// ◆给原型添加方法
Person.prototype.eat = function () {
console.log(`我喜欢吃汉堡包`)
}
Person.prototype.sayHi = function () {
console.log(`我是${this.name},今年${this.age}岁了`)
}
// ◆实例对象
let p1 = new Person('小爱同学', 20)
p1.eat()//我喜欢吃汉堡包
p1.sayHi()//我是小爱同学,今年20岁了
console.log(p1)//Person { name: '小爱同学', age: 20 }
</script>
瞧瞧 ES6 的 继承
底层原理相当于 Child.prototype.__proto__ = Parent.prototype
<script>
// ◆使用 class 构造一个父类
class Parent {
constructor(name, age) {
this.name = name
this.age = age
}
// ◆给 Parent 的原型添加方法 : 方法名(){}
sayHi() {
console.log(`我是${this.name},我今年${this.age}岁了`)
}
}
// ◆使用class 构造一个子类,并使用 extends 实现继承,super 指向父类的原型对象
class Child extends Parent {
constructor(name, age, gender) {
// ◆super() 子类中调用父类的方法
super(name, age)
this.gender = gender
}
// ◆给 Child 的原型添加方法 : 方法名(){}
sayGender() {
console.log(this.gender)
}
}
// ◆实例化对象
const p1 = new Child('Lucy', 18, '女')
p1.sayGender()//女
p1.sayHi()//我是Lucy,我今年18岁了
console.log(p1)//Child {name: 'Lucy', age: 18, gender: '女'}
</script>
class本质其实就是构造函数的另一种写法,本质还是给prototype添加成员,使用了class,一样可以继续使用ES5的prototype