• 关于继承的prototype , _proto_, constructor


    1. 最常见的组合式继承

    function Parent(p)
    {
      this.p = p;
    } 
    Parent.prototype.get = function() {   //注:prototype其中就是一个空对象{},但它是function特有的对象
       return this.p;
    }
    
    function Child(c)
    {
       Parent.call(this,c);  //继承Parent的属性
      
    this.c = 3; }

    Child.prototype = new Parent(); //现在,child.prototype对象就是Parent的实例,则里面含有 实例属性: p ,目前的值为 undefined,同时此时的
                       //Child.prototype.constructor = Parent ;

    var c = new Child(); //在c中又会有一份 实例属性p ;

    这是因为:
    在new Parent的时候,调用了一次 Parent的构造函数;
    当调用Child的构造函数的时候,又调用了一次Parent的构造函数,又会在新对象上创建实例属性 p ;

    为了避免这种重复创建属性的过程,

    可以选择1 :及时修正
    Child.prototype = new Parent();
    Child.prototype.constructor = Child; //这可以避免 二次 创建,但是 一次创建的东西是 不会消失啦,也就是Child.prototype中保留着一份 实例属性


    选择2 :改变继承方式:寄生组合式继承
    function inheritPrototype( w, m)
    {
    var p = Object(w.prototype);
    p.constructor = m;
    m.prototype = p;
    }

    //属性继承不变
    function Child(c)
    {
    Parent.call(this,c);
    this.c = c;
    }
    inheritPrototype( Parent ,Child );

    点评一下: 其实这个方法是先 偷梁换柱,再交还给 子类

    选择3 :野生方法(好像不好看,不过很管用啊,可能效率有点低啦!)
    function Child( c)
    {
    Parent.call(this,c);
    this.c = c;
    }
    for( var i in Parent.prototype )
    {
    Child.prototype[i] = Parent.prototype[i];
    }
    这样继承的话,Child.pototype.constructor 的值 还是Child 啦!而且Child.prototype中也不会有实例 属性 p;

    其实,2、3差不多啦!

  • 相关阅读:
    wince 操作sqlite数据库
    c#数据结构(第二章)
    C#数据结构(第三章)
    近期学习(收藏地址)
    c#数据结构(第四章)
    PowerDesigner 数据库设计
    wince操作远程sqlserver数据库
    一个有趣的算法
    c#数据结构(第一章)
    c#实现显示图片的动态效果
  • 原文地址:https://www.cnblogs.com/shixiaomiao/p/5232813.html
Copyright © 2020-2023  润新知