美文网首页
继承的发展

继承的发展

作者: 灯火葳蕤234 | 来源:发表于2019-10-05 20:24 被阅读0次
    1.传统形式 ——原型链

    缺点:过多地继承了没用的属性
    举例:

    Grand.prototype.lastName = 'Li';
    function Grand() {
    }
    var grand = new Grand();
    Father.prototype = grand;
    function Father() {
      this.name = 'li';
    }
    var father = new Father();
    Son.prototype = father;
    function Son(){
    }
    var son = new Son();
    

    比如以上的情况,我们只是想在 son 实例中去继承原型链顶端的 lastName 属性,但是我们把原型链上所有的属性都继承过来了。所以这个继承的方法其实是不太好的。

    2.借用构造函数

    缺点:不能继承借用构造函数的原型
    每次构造函数都要多走一个函数
    举例:

    function Person(name,age,sex){
      this.name = name;
      this.age = age;
      this.sex = sex;
    }
    function Student(name,age,sex,grade) {
      Person.call(this,name,age,sex);
      this.grade = grade;
    }
    var student = new Student();
    
    3.公有原型

    缺点:不能随便改动自己的原型
    举例:

    Father.prototype.lastName = 'Li';
    function Father() {
    }
    function Son() {
    }
    Son.prototype = Father.prototype;
    var son = new Son(); //son.lastName = 'Li';
    var father = new Father();//father.lastName = 'Li';
    

    我们可以把继承的逻辑封装成一个功能:

    Father.prototype.lastName = 'Li';
    function Father() {
    }
    function Son() {
    }
    function inherit(Target,Origin){
      Target.prototype = Origin.prototype;
    }
    inherit(Son, Father);
    

    但是这个方法依旧有不足的地方,比如我们想要给Son 的原型上多加一个属性来方便它构造出对象来使用,此时我们只有在 Son.prototype 中去增加属性,但是,这样会影响 Father.prototype,原因是Son.prototypeFather.prototype指向的其实是同一片内存空间。在这种情况下,我们想给Son 加上个性化的属性是不可行的。

    4.圣杯模式

    这个方法解决了公有原型方法的问题,是比较理想的继承的方法。

    funnction inherit(Target, Origin){
      function F(){};
      F.prototype = Origin.prototype;
      Target.prototype = new F();
      Target.prototype.constuctor = Target;//归位Son的constuctor
      Target.prototype.uber = Origin.prootype;//找到真正继承自谁
    }
    Father.prototype.lastName = 'Li';
    function Father() {
    }
    function Son() {
    }
    inherit(Son, Father);
    var son = new Son();
    var father = new Father();
    

    相关文章

      网友评论

          本文标题:继承的发展

          本文链接:https://www.haomeiwen.com/subject/pvynyctx.html