zoukankan      html  css  js  c++  java
  • 原型重写问题

    (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

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

  • 相关阅读:
    elasticsearch 5.x 系列之七 基于索引别名的零停机升级服务
    Linux 查看系统硬件信息(实例详解)
    linux grep命令详解
    Boot loader: Grub进阶(转)
    Boot loader: Grub入门(转)
    内核模块管理(转)
    Centos启动流程(转)
    Linux 内核启动流程(转)
    程序的运行顺序(转)
    查询进程打开的文件(转)
  • 原文地址:https://www.cnblogs.com/psxiao/p/11372163.html
Copyright © 2011-2022 走看看