原型链继承: 原理:将父类的实例作为子类的原型

      function Father(){
        this.age=10
        this.phone={
          first:"华为",
          second:"小米"
        }
      }
      Father.prototype.getage=function(){
        return this.age
      }
      function Son(name,money){
        this.name=name
        this.money=money
      }
      Son.prototype=new Father() //子类型的原型为父类型的一个实例对象
      Son.prototype.constructor=Son //让子类型的原型的constructor指向子类型
      Son.prototype.getmoney=function(){
        return this.money
      }
      var son=new Son("小米",1000)//
      var son2=new Son()
      console.log(son.age)//10
      console.log(son.getage())//10
      console.log(son.name)//小米
      console.log(son.getmoney())//1000
      console.log(son instanceof Son)//true
      console.log(son instanceof Father)//true
      son.phone.first="魅族"//更改一个子类的引用属性,其他子类也会受影响
      console.log(son2.phone.first)//魅族

 

  优点:1.通过子类实例可以直接访问父类原型链上和实例上的成员

                      2.  相对简单

           缺点:1.创建子类实例时,无法向父类构造函数传参

                      2.父类的所有引用属性会被所有子类共享,更改一个子类的引用属性,其他子类也会受影响

二.构造函数继承:
       原理:在子类构造函数中调用父类构造函数,可以在子类构造函数中使用call()和apply()方  法改变this指向

      function Father(name,age){
        this.name=name
        this.age={age:age}
      }
      Father.prototype.getname=function(){
        return this.name
      }
      function Son(name,age,money){
        Father.call(this,name,age)//修改Father的this
        this.money=money
      }
      Son.prototype.getmoney=function(){
        return this.money
      }
      var son=new Son("小明",12,1000)
      var son2=new Son("小李",11,999)
      console.log(son.name)//小明
      console.log(son.getname())//报错 无法继承父类原型上的属性与方法
      console.log(son.money)//1000
      console.log(son.getmoney())//1000
      console.log(son instanceof Father)//false
      console.log(son instanceof Son)//true
      console.log(son.age.age)//12
      console.log(son2.age.age)//11 父类的引用属性不会被共享

 

    优点:1.可以在子类实例中直接向父类构造函数传参

                   2.父类的引用属性不会被子类共享

        缺点:1.无法继承父类原型上的属性与方法

你可能感兴趣的:(javascript,原型模式,前端)