js继承的方法和优缺点
1.原型链继承
实现方式:将子类的原型链指向父类的对象实例
function Parent(){
this.name = 'parent'
this.list = ['a']
}
Parent.prototype.sayHi = function(){
console.log('hi')
}
function Child(){
}
Child.prototype = new Parent()
var child = new Child()
console.log(child.name)
child.sayHi()
原理:子类实例child的__proto__指向Child的原型链prototype,而Child.prototype指向Parent类的对象实例,该父类对象实例的__proto__指向Parent.prototype,所以Child可继承Parent的构造函数属性、方法
优点:可继承构造函数的数学,父类构造函数的数学,父类原型的数学
缺点:无法向父类构造函数传参;且所有实例共享父类实例的数学,若父类共有属性为引用类型,一个类实例更改父类构造函数共有属性时会导致继承的共有属性发生变化;实例如下:
var a = new Child()
var b = new Child()
a.list.push('b')
console.log(b.list)
2.构造函数继承
实现方式:在子类构造函数中使用call或者apply劫持父类构造函数方法,并传入参数
function Parent(name,id){
this.id = id
this.name = name
this.printName = function(){
console.log(this.name)
}
}
Parent.prototype.sayName = function(){
console.log(this.name)
}
function Child(name,id){
Parent.call(this,name,id)
}
var child = new Child('jin','1')
child.printName();//jin
child.sayName()//Error