javascript
JavaScript中的三种常用继承方法
目錄
1.原型鏈繼承
2.借用構(gòu)造函數(shù)繼承(繼承屬性)
3.組合繼承
4.使用call或apply向父函數(shù)中傳參
?
1.原型鏈繼承
固定格式:
子函數(shù).prototype=new 父函數(shù)();原理:通過改變一個(gè)函數(shù)的原型指向來完成的繼承
優(yōu)點(diǎn):暫無(2021.2.18)
缺點(diǎn):
示例代碼:
//Humans是父函數(shù),Mans是子函數(shù)function Humans(){this.foot=2; }Humans.prototype.getFoot=function(){alert(this.foot); }function Mans(){this.head=3; }Mans.prototype=new Humans(); //Mans繼承HumansMans.prototype.getHead=function(){ //注意向子類原型中添加屬性或方法要寫在繼承語句之后 alert(this.head); }var man1=new Mans(); man1.getFoot(); man1.getHead();?
2.借用構(gòu)造函數(shù)繼承(繼承屬性)
在子函數(shù)內(nèi)部使用apply或者call完成構(gòu)造函數(shù)繼承
固定格式:
//語法卸載子函數(shù)函數(shù)體內(nèi)//使用apply 父函數(shù).apply(this);//使用call 父函數(shù).call(this);原理:此繼承相當(dāng)于把父函數(shù)函數(shù)體內(nèi)的屬性或方法拷貝了一份副本給子函數(shù)的實(shí)例使用
優(yōu)點(diǎn):子函數(shù)實(shí)例不共用同一個(gè)父函數(shù)的屬性或方法,修改一處不會導(dǎo)致全局被修改,可以向父函數(shù)傳參(2021.2.18)
缺點(diǎn):只能繼承父函數(shù)函數(shù)體內(nèi)的屬性或方法,無法繼承原型中的任何東西
示例代碼:
//Humans是父函數(shù),Mans是子函數(shù)function Humans(){this.foot=2; }Humans.prototype.getFoot=function(){alert(this.foot); }function Mans(){this.head=3;Humans.call(this); }Mans.prototype.getHead=function(){ //注意向子類原型中添加屬性或方法要寫在繼承語句之后 alert(this.head); }var man1=new Mans();alert(man1.foot); alert(man1.head);?
3.組合繼承
使用原型鏈繼承和借用構(gòu)造函數(shù)繼承實(shí)現(xiàn)組合繼承
固定格式:
//語法寫在子函數(shù)函數(shù)體內(nèi)//使用apply 父函數(shù).apply(this);//使用call 父函數(shù).call(this);//原型鏈繼承 子函數(shù).prototype=new 父函數(shù)();原理:借用構(gòu)造函數(shù)繼承父函數(shù)函數(shù)體內(nèi)的東西,原型鏈繼承父函數(shù)原型中的東西(彌補(bǔ)了結(jié)構(gòu)構(gòu)造函數(shù)的缺點(diǎn))
優(yōu)點(diǎn):子函數(shù)實(shí)例不共用同一個(gè)父函數(shù)的屬性或方法,修改一處不會導(dǎo)致全局被修改,可以向父函數(shù)傳參,同時(shí)子函數(shù)又繼承父函數(shù)的原型(2021.2.18)
缺點(diǎn):暫無
示例代碼:
//Humans是父函數(shù),Mans是子函數(shù)function Humans(){this.foot=2; }Humans.prototype.getFoot=function(){alert(this.foot); }function Mans(){this.head=3;Humans.call(this); //繼承屬性 }Mans.prototype=new Humans(); //繼承原型Mans.prototype.getHead=function(){ //注意向子類原型中添加屬性或方法要寫在繼承語句之后 alert(this.head); }var man1=new Mans();alert(man1.foot); alert(man1.head); man1.getFoot();?
4.使用call向父函數(shù)中傳參
固定格式:
//參數(shù)傳遞的順序和父函數(shù)()中參數(shù)的順序一致 父函數(shù).call(this,參數(shù)1,參數(shù)2....)示例代碼:
//Humans是父函數(shù),Mans是子函數(shù)function Humans(foot){ //注意,此時(shí)()里的foot和函數(shù)體內(nèi)的foot不是一個(gè)footthis.foot=foot; //this.foot=參數(shù)foot }Humans.prototype.getFoot=function(){alert(this.foot); }function Mans(){this.head=3;Humans.call(this,2); //繼承屬性 }Mans.prototype=new Humans(); //繼承原型Mans.prototype.getHead=function(){ //注意向子類原型中添加屬性或方法要寫在繼承語句之后 alert(this.head); }var man1=new Mans();alert(man1.foot); alert(man1.head); man1.getFoot();聲明:所有內(nèi)容均為個(gè)人理解總結(jié),如理解有誤請及時(shí)糾正我的錯(cuò)誤,以免誤人子弟,謝謝!!!
總結(jié)
以上是生活随笔為你收集整理的JavaScript中的三种常用继承方法的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 我的世界钟表(我的世界钟)
- 下一篇: oppo怎么截长图(oppo怎么截图)