首頁 > web前端 > js教程 > 主體

javascript組合式繼承並解決兩次呼叫問題程式碼詳解

伊谢尔伦
發布: 2017-07-20 16:32:59
原創
1896 人瀏覽過

組合式繼承是比較常用的一種繼承方法,其背後的想法是 使用原型鏈實現對原型屬性和方法的繼承,而藉由借用建構函式來實現實例屬性的繼承。這樣,既透過在原型上定義方法實現了函數復用,又保證每個實例都有它自己的屬性。

<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中文網其他相關文章!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
最新問題
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!