首页  >  文章  >  web前端  >  javascript组合式继承和解决两次调用问题代码详解

javascript组合式继承和解决两次调用问题代码详解

伊谢尔伦
伊谢尔伦原创
2017-07-20 16:32:591898浏览

组合式继承是比较常用的一种继承方法,其背后的思路是 使用原型链实现对原型属性和方法的继承,而通过借用构造函数来实现对实例属性的继承。这样,既通过在原型上定义方法实现了函数复用,又保证每个实例都有它自己的属性。

<script>
    function Parent(age){
        this.name = [&#39;mike&#39;,&#39;jack&#39;,&#39;smith&#39;];
        this.age = age;
    }
    Parent.prototype.run = function () {
        return this.name  + &#39; are both&#39; + this.age;
    };
    function Child(age){
        Parent.call(this,age);//对象冒充,给超类型传参
    }
    Child.prototype = new Parent();//原型链继承
    var test = new Child(21);//写new Parent(21)也行
    alert(test.run());//mike,jack,smith are both21
</script>

组合式继承的小问题

组合式继承是js最常用的继承模式,但组合继承的超类型在使用过程中会被调用两次;一次是创建子类型的时候,另一次是在子类型构造函数的内部

<script>
    function Parent(name){
        this.name = name;
        this.arr = [&#39;哥哥&#39;,&#39;妹妹&#39;,&#39;父母&#39;];
    }
    Parent.prototype.run = function () {
        return this.name;
    };
    function Child(name,age){
        Parent.call(this,age);//第二次调用
        this.age = age;
    }
    Child.prototype = new Parent();//第一次调用
</script>

以上代码是之前的组合继承,那么寄生组合继承,解决了两次调用的问题。

<script>
       function F(){}
        F.prototype = o;
        return new F();
    }
    function create(parent,test){
        var f = obj(parent.prototype);//创建对象
        f.constructor = test;//增强对象
    }

    function Parent(name){
        this.name = name;
        this.arr = [&#39;brother&#39;,&#39;sister&#39;,&#39;parents&#39;];
    }
    Parent.prototype.run = function () {
        return this.name;
    };
    function Child(name,age){
        Parent.call(this,name);
        this.age =age;
    }
    inheritPrototype(Parent,Child);//通过这里实现继承
    var test = new Child(&#39;trigkit4&#39;,21);
    test.arr.push(&#39;nephew&#39;);
    alert(test.arr);//
    alert(test.run());//只共享了方法
    var test2 = new Child(&#39;jack&#39;,22);
    alert(test2.arr);//引用问题解决
</script>

 

以上是javascript组合式继承和解决两次调用问题代码详解的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn