天天看點

js 繼承(1)

js 如何實作繼承呢?

下面是一個簡單的繼承demo

js 繼承(1)

console.clear();  

//child 繼承 parent  

var extend=function(child,parent)  

{  

  child.prototype=new parent();  

}  

function a(){  

  this.name="a";  

  this.sayhello=function(){  

    console.log("hello , "+this.name);  

  }  

function b(){  

  this.sex='man';  

  this.mysex=function(){  

    console.log("sex:"+this.sex);  

extend(b,a);  

var b=new b();  

b.mysex();  

b.sayhello();  

 運作結果:

sex:man

hello , a

說明:b 本身沒有sayhello 方法,而是從a 繼承過來的.

那麼我們再讓b繼承另外一個類c 

js 繼承(1)

function c(){  

  this.age=26;  

  this.myage=function(){  

    console.log("age:"+this.age);  

extend(b,c);  

 報錯:

js 繼承(1)

 繼承c 之後,調用sayhello竟然報錯,但是sayhello不是從a 繼承過來的嗎?

說明我們的繼承方法有問題:

js 繼承(1)

 b先繼承a,然後繼承c,那麼之前繼承a的屬性都沒了.這顯然不合要求.

是以我優化一下繼承方法:

js 繼承(1)

  var p1=child.prototype;  

  child.prototype.__proto__=p1;  

 完整代碼如下:

js 繼承(1)

b.myage();  

 執行結果:

age:26

js 繼承(1)

即b 成功地調用了a和c 的方法

 我們繼續優化,因為__proto__在ie中不能通路.

優化的結果:

js 繼承(1)

       var extend=function(child,parent)  

       {  

           var p1=child.prototype;  

           var p2=parent.prototype;  

           parent.prototype=p1;  

           child.prototype=new parent();  

           parent.prototype=p2;  

       }  

       function a(){  

           this.name="a";  

           this.sayhello=function(){  

               console.dir("hello , "+this.name);  

           }  

       function b(){  

           this.sex='man';  

           this.mysex=function(){  

               console.dir("sex:"+this.sex);  

       function c(){  

           this.age=26;  

           this.myage=function(){  

               console.dir("age:"+this.age);  

       extend(b,a);  

       extend(b,c);  

       var b=new b();  

       b.mysex();  

       b.sayhello();  

       b.myage();  

       console.dir(a);  

       console.dir(b);  

       console.dir(c);  

js 繼承(1)

 繼承方法:

js 繼承(1)

           delete p1;  

           delete p2;  

       }  

繼續閱讀