组合寄生、寄生、原型式。。。。这么多叫法,记不住啊,晕。。下面几种都是在两个概念上进行优化的,记住原理就好,实在不用记住它的叫法。
原型链
function Parent(){
this.name = 'luffy'
this.arr = [1,2,3,4]
}
Parent.prototype.getName = function(){
return this.name
}
function Child(age){
this.age = age
}
Child.prototype = new Parent()
Child.prototype.getAge = function(){
return this.age
}
//因为child.prototype被重新定义,导致constructor改变
Child.prototype.constructor = Child
let c = new Child(3)
问题:
- 这里把child的原型设置为父类的一个实例,导致后面的实例c可以操作父类的任何属性和方法(简单)
- 实例化的所有子类共享父类的属性和方法,一旦改变其中有个属性被改了,影响所有实例(粗暴)
- 不能给父类传递参数
构造函数
function Parent(name){
this.name = name
this.arr = [1,2,3,4]
}
Parent.prototype.getName = function(){
return this.name
}
function Child(age,name){
this.age = age
Parent.call(this,name)
}
Child.prototype.getAge = function(){
return this.age
}
var c = new Child(3,'luffy')
解决了上述问题中的2,3,还不用手动改constructor方法
问题:
- 子类无法继承父类原型上的属性和方法
原型链+构造函数
将上面的两种方法结合在一起就好啦
function Parent(name){
this.name = name
this.arr = [1,2,3,4]
}
Parent.prototype.getName = function(){
return this.name
}
function Child(age,name){
this.age = age
Parent.call(this,name)
}
Child.prototype = new Parent()
Child.prototype.getAge = function(){
return this.age
}
Child.prototype.constructor = Child
var c = new Child(3,'luffy')
问题:
- 重复的调用了父类的构造函数(调用2次)
优化1.Object.create()
function Parent(name){
this.name = name
this.arr = [1,2,3,4]
}
Parent.prototype.getName = function(){
return this.name
}
//注意这句,不同的实例如果改变了引用类型属性books,相互影响
//但是非引用类型的属性根本不存在这种改变,如果 c.like = 90,会给c的实例上添加同名属性,覆盖原型上的
Parent.prototype.books = [1,2,3]
Parent.prototype.like = 0
function Child(age,name){
this.age = age
Parent.call(this,name)
}
Child.prototype = Object.create(Parent.prototype,{
getAget:{
value:function(){
return this.age
}
}
})
Child.prototype.constructor = Child
var c = new Child(3,'luffy')
欢迎继续补充优化。