组合继承(类与类的方法)
- 通过构造函数(继承父类属性)+原型对象(父类方法)
通过构造函数继承(继承父类属性)
function Parent(name) {
this.name = name; // 实例基本属性 (该属性,强调私有,不共享)
this.arr = [1]; // (该属性,强调私有)
}
function Child(name, like) {
Parent.call(this, name, like) // 核⼼ 第一个参数是this现在指向哪里+name(父函数的参数)
this.like = like;//孩子可以添加自己的属性
}`
通过原型对象(继承父类方法)
Parent.prototype.say = function () { // --- 将需要复⽤、共享的⽅法定义在⽗类原型上
console.log('hello')
}
Child.prototype = new Parent() // 核⼼ 第⼀次
Child.prototype.constructor = Child // 修正constructor指向
组合继承优化
// 核⼼ 通过创建中间对象,⼦类原型和⽗类原型,就会隔离开。不是同⼀个啦,有效避免了⽅式4的缺点。
Child.prototype = Object.create(Parent.prototype)
// 这⾥是修复构造函数指向的代码
Child.prototype.constructor = Child
es6通过类继承
super必须放到this之前
class Parent {
constructor(name) {
this.name = name;
}
getName() {}
}
class Child extends Parent {
constructor(name, age) {
super(name);
this.age = age;
}
getAge() {}
}
let person = new Child('Demi', 24)
console.log(person) // {name: 'Demi', age: 24}