JS的繼承是從一個對象原型向另一個對象原型的簡單拷貝

 

JavaScript支持面向對象,但是其實現方式是通過簡單的從一個對象原型向另一個對象原型的拷貝的方式來實現的。 

實例如下:

 

[javascript] 

var BaseCls={};  

  

BaseCls.getName=function(){  

    return "base class";  

}  

  

  

var ChildCls = {};  

  

ChildCls.getName = BaseCls.getName;  

  

BaseCls.getName=function(){  

    return "base class changed";  

}  

  

alert(ChildCls.getName());  

  

alert(BaseCls.getName());  

 

var BaseCls={};

 

BaseCls.getName=function(){

return "base class";

}

 

 

var ChildCls = {};

 

ChildCls.getName = BaseCls.getName;

 

BaseCls.getName=function(){

return "base class changed";

}

 

alert(ChildCls.getName());

 

alert(BaseCls.getName());ChildCls.getName = BaseCls.getName;是將BaseCls的getName的定義復制給ChildCls的getName函數,之後對BaseCls的getName的改變不會影響到ChildCls的getName函數。

 

同樣,用prototype繼承也是相同的效果:

 

 

[javascript]

var BaseCls={};  

  

BaseCls.getName=function(){  

    return "base class";  

}  

  

function ChildCls(){  

      

}  

  

ChildCls.prototype.getName = BaseCls.getName;  

  

BaseCls.getName=function(){  

    return "base class changed";  

}  

  

alert(new ChildCls().getName());  

  

alert(BaseCls.getName());  

 

var BaseCls={};

 

BaseCls.getName=function(){

return "base class";

}

 

function ChildCls(){

 

}

 

ChildCls.prototype.getName = BaseCls.getName;

 

BaseCls.getName=function(){

return "base class changed";

}

 

alert(new ChildCls().getName());

 

alert(BaseCls.getName());

 

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *