JS组合继承:
继承作用:减少代码,是用来优化代码的
JS中不用继承也可以(用不用都可以)
一、属性继承:
function Father(name, age) {
this.name = name
this.age = age
}
function Son(name, age,price) {
// 实现了属性继承
// 此处的this指向的是:Son构造函数创建的实例对象
// 相当于是p1.name = name p1.age = age
Father.call(this, name, age)
this.price = price
}
let p1 = new Son('Alex', 22,12000)
console.log(p1)
实现属性继承总结:
1) 在Fn2构造函数中调用Fn1构造函数
2) 修改Fn1构造函数中的this指向
3) 将Fn1中的this指向修改为Fn2中的this指向,那就是this
4) 在继承的时候,如果需要单独设置属性,则可以在自己的构造函数中单独添加即可
二、方法继承:
function Father(name, age) {
this.name = name
this.age = age
}
// 向Father原型对象身上添加了一个eat方法
Father.prototype.eat = function () {
console.log('吃三个馒头')
}
function Son(name, age, price) {
Father.call(this, name, age)
this.price = price
}
// 实现了方法继承 推荐的写法
// 让Son的原型对象成为Father的实例对象,可以使用Father中的方法
Son.prototype = new Father()
let per1 = new Son('Alex', 23, 18000)
per1.eat()
JS继承总结:
1.通过call()方法实现了构造函数的属性继承
2.通过prototype原型对象实现了构造函数的方法继承