组合寄生、寄生、原型式。。。。这么多叫法,记不住啊,晕。。下面几种都是在两个概念上进行优化的,记住原理就好,实在不用记住它的叫法。

原型链

  1. function Parent(){
  2. this.name = 'luffy'
  3. this.arr = [1,2,3,4]
  4. }
  5. Parent.prototype.getName = function(){
  6. return this.name
  7. }
  8. function Child(age){
  9. this.age = age
  10. }
  11. Child.prototype = new Parent()
  12. Child.prototype.getAge = function(){
  13. return this.age
  14. }
  15. //因为child.prototype被重新定义,导致constructor改变
  16. Child.prototype.constructor = Child
  17. let c = new Child(3)

问题:

  1. 这里把child的原型设置为父类的一个实例,导致后面的实例c可以操作父类的任何属性和方法(简单)
  2. 实例化的所有子类共享父类的属性和方法,一旦改变其中有个属性被改了,影响所有实例(粗暴)
  3. 不能给父类传递参数

构造函数

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方法

问题:

  1. 子类无法继承父类原型上的属性和方法

原型链+构造函数

将上面的两种方法结合在一起就好啦

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')

问题:

  1. 重复的调用了父类的构造函数(调用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')

欢迎继续补充优化。