• 原型重写问题


    (1)

    function Aa(name){
      this.name = name;
      this.colors = ["red","blue","green"];
    }

    Aa.prototype.sayName = function(){
      console.log(this.name)
    }
    function Bb(name,age){
      Aa.call(this,name);
      this.age = age;
    }
    var b = new Bb()
    // console.log(b.sayName)
    console.log(Aa.prototype)


    Bb.prototype.sayAge = function (){
      console.log(this.age)
    }
    Bb.prototype.ue="ni"

    console.log(Bb.prototype)

    未重写Bb.prototype原型前,Aa.prototype原型所包含的属性方法有一下这些:

    未重写Bb.prototype原型前,Bb.prototype原型所包含的属性方法有一下这些:

    同样这里,实例b也不能访问Aa的原型方法和属性

    (2)

    function Aa(name){
      this.name = name;
      this.colors = ["red","blue","green"];
    }

    Aa.prototype.sayName = function(){
      console.log(this.name)
    }
    function Bb(name,age){
      Aa.call(this,name);
      this.age = age;
    }
    var b = new Bb()
    // console.log(b.sayName)
    console.log(Aa.prototype)


    Bb.prototype.sayAge = function (){
      console.log(this.age)
    }
    Bb.prototype.ue="ni"

    console.log(Bb.prototype)

    //重写Bb.prototype
    Bb.prototype = new Aa();
    Bb.prototype.constructor = Bb;
    console.log(Bb.prototype)

     console.log(instance.ue)//undefined
    instance.sayAge()//直接报错,说instance.sayAge is not a function

    重写Bb.prototype后,Bb.prototype的属性和方法:将Aa构造函数的属性和原型的方法都继承过来了,但是替换前添加的Bb原型对象的方法和属性都将被重写,所以当Bb的实例instance访问Bb的原型属性ue是会打印出undefined

    当访问sayAge是,会报错instance.sayAge is not a function

     总结:为了避免超类型构造函数不会重写子类型的属性,可以在调用超类型构造函数后,再添加应该再子类型中定义的属性和方法

  • 相关阅读:
    ABP框架系列之三十六:(MVC-Views-MVC视图)
    ABP框架系列之三十五:(MVC-Controllers-MVC控制器)
    ABP框架系列之三十四:(Multi-Tenancy-多租户)
    ABP框架系列之三十三:(Module-System-模块系统)
    2-kong的preserve_host和strip_uri解析
    2-Consul简介
    1-Consul系列文章
    1-Kong文章记录
    1-ES学些教程
    0-Jenkins系列学习文章
  • 原文地址:https://www.cnblogs.com/psxiao/p/11372163.html
Copyright © 2020-2023  润新知