JS中的原型繼承和多重繼承


概念:1原型繼承是創建新類型對象----子類型,子類型基於父類型,子類型擁有父類型所有的屬性和方法(從父類型繼承得到),然后修改其中的部分內容或者添加新的內容。繼承最好在子類型模型可以被視為父類型對象的時候使用。

    2從多個父類型中派生出一個對象類型稱為多重繼承。

原型繼承:

使用new關鍵字和構造函數的prototype屬性都是定義類型的特定方式,這些是我們到目前為止一直使用的,對於簡單的對象,這種方式還是很好的,但是當程序過度使用繼承時,這種創建對象的方法很快就顯得笨拙了。所以增加一些函數作為常用操作符可以使其順利一些。例如很多人都在對象上定義inherit方法和method方法。

        Object.prototype.inherit=function(baseConstructor){
            this.prototype = clone(baseConstructor.prototype);
            this.prototype.constructor=this;
        };
        Object.prototype.method=function(name,func){
            this.prototype[name]=func;
        };    


有了上面的信息,就可以像下面這樣編碼

        function StrangeArray(){}
        StrangeArray.inherit(Array);
        StrangeArray.method("push",function(value){
            Array.prototype.push.call(this,value);
            Array.prototype.push.call(this,value);
        });
        var strange=new StrangeArray();
        strange.push(4);//輸出[4,4]


多重繼承(混合類型):

實現多重繼承的方式很多,下面的一個小例子是比較簡單的而且多數情況下都適用的。

mix-in是一種特殊的原型,它可以混入到其他的原型里。SmallItem可以看做這樣的一個原型。通過將它的方法復制到另一個原型里,其自身也混入了那個復制方法的原型。

        function mixInto(object,mixIn){
            forEachIn(mixIn,function(name,value){
                object[name] = value;

            });
        };
        var SmallDetailedItem = clone(DetailedItem);
        mixInto(SmallDetailedItem,SmallItem);

        var deadMouse = SmallDetailedItem.create("Fred the mouse","he is dead");
        deadMouse.inspect();
        deadMouse.kick();

還有下面的例子就是三種繼承的實現。

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <script>
//The first way
function Person(name) { this.name = name; } Person.prototype.getName = function() { return this.name; } function Author(name, books) { this.books = books; } Author.prototype=new Person(name); Author.prototype.constructor=Author; Author.prototype.getBooks = function() { return this.books; } var au1=new Author("dororo1","Learn much"); var au2=new Author("dororo2","Learn less"); alert(au1.getName()); alert(au2.getName()); //The second way function Person(name) { this.name = name; } Person.prototype.getName = function() { return this.name; } function Author(name, books) { this.inherit=person; this.inherit(name); this.books = books; } var au=new Author("dororo","Learn much"); alert(au.getName()) ; //The thrid way function Person(name) { this.name = name; } Person.prototype.getName = function() { return this.name; } function Author(name, books) { this.base = new Person(name); for(var key in this.base){ if(!this[key]){ this[key]=this.base[key]; } } this.book=books; } var au1=new Author("dororo1","work"); var au2=new Author("dororo2","play"); alert(au1.getName()); alert(au2.getName()); au1.book; au2.book; </script> </head> <body> </body> </html>

 *part of the article from <<Eloquent JavaScript>>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM