ES5 实现继承
最后更新于:2022-04-02 03:24:30
[TOC]
## 继承
```
function create(proto) {
function F() {}
F.prototype = proto;
return new F();
}
// Parent
function Parent(name) {
this.name = name
}
// 父类方法
Parent.prototype.sayName = function () {
console.log(this.name)
};
// Child
function Child(age, name) {
Parent.call(this, name)
this.age = age
}
// 继承父类方法
Child.prototype = create(Parent.prototype)
// 子类方法
Child.prototype.sayAge = function () {
console.log(this.age)
}
// 测试
const child = new Child(18, 'Jack')
child.sayName() // Jack
child.sayAge() // 18
```
';