Father作为父类,Child作为子类,继承的目标是让子类可以访问到父类的属性和方法
function Father () {
this.name = name
this.age = age
this.run = function () {
console.log('加油')
}
}
function Child (name, age) {}
let tom = new Child()
1.原型链继承
实现简单、方便理解。就是将父类挂载在子类的prototype上。
function Father () {
this.run = function () {
console.log('加油')
}
}
function Child (name, age) {
this.name = name
this.age = age
}
Child.prototype = new Father()
let tom = new Child('tom', 6)
tom.run() // 加油
console.log(tom.name) // tom
console.log(tom.age) // 6
缺点:无法实现多继承
2.构造继承(利用call、apply的特性实现)
利用call或者apply改变子类的this指向。从而实现在子类中调用父类的方法
function Father (name, age) {
this.name = name
this.age = age
this.run = function () {
console.log('加油')
}
}
function Child (name, age) {
Father.call(this, ...arguments)
}
Child.prototype = new Father()
let tom = new Child()
tom.run() // 加油
缺点:只能继承父类的实例,不能继承父类的原型
3.组合继承(原型链继承+构造继承)
结合原型链继承和构造继承的优点(推荐使用)
function Father (name, age) {
this.name = name
this.age = age
this.run = function () {
console.log('加油')
}
}
function Child (name, age) {
Father.apply(this, arguments)
}
Child.prototype = new Father()
let tom = new Child('tom', 19)
tom.run() // 加油
console.log(tom.name)
console.log(tom.age)
4.原型继承或者叫实例继承
对子类进行函数封装且返回父类,new Child() --> 相当于 new Father()。从而实现继承
function Father (name) {
this.name = name
this.run = function () {
console.log('加油')
}
}
function Child (name) {
let instance = new Father(...arguments);
return instance;
}
let tom = new Child('tom')
tom.run() // 加油
console.log(tom.name)
5.拷贝继承
利用for in 循环将父类的属性进行循环往子类的prototype中添加。
function Father () {
this.run = function () {
console.log('加油')
}
}
function Child(name){
let father = new Father();
for(let p in father){
Child.prototype[p] = father[p];
}
Child.prototype.name = name;
}
let tom = new Child('tom')
tom.run()
console.log(tom.name)
缺点:执行效率比较低
网友评论