js的三種繼承方式詳解
1.js原型(prototype)實(shí)現(xiàn)繼承
代碼如下
<body>
<script type="text/javascript">
function Parent(name,age){
this.name=name;
this.age=age;
this.sayHi=function(){
alert("Hi, my name is "+this.name+", my age is "+this.age);
}
}
//Child繼承Parent
function Child(grade){
this.grade=grade;
this.sayGrade=function(){
alert("My grade is "+this.grade);
}
}
Child.prototype=new Parent("小明","10");///////////
var chi=new Child("5");
chi.sayHi();
chi.sayGrade();
</script>
</body>
2.構(gòu)造函數(shù)實(shí)現(xiàn)繼承
代碼如下:
<body>
<script type="text/javascript">
function Parent(name,age){
this.name=name;
this.age=age;
this.sayHi=function(){
alert("Hi, my name is "+this.name+", my age is "+this.age);
}
}
//Child繼承Parent
function Child(name,age,grade){
this.grade=grade;
this.sayHi=Parent;///////////
this.sayHi(name,age);
this.sayGrade=function(){
alert("My grade is "+this.grade);
}
}
var chi=new Child("小明","10","5");
chi.sayHi();
chi.sayGrade();
</script>
</body>
3.call , apply實(shí)現(xiàn)繼承 -----很方便!
代碼如下:
<body>
<script type="text/javascript">
function Parent(name,age){
this.name=name;
this.age=age;
this.sayHi=function(){
alert("Hi, my name is "+this.name+", my age is "+this.age);
}
}
function Child(name,age,grade){
this.grade=grade;
// Parent.call(this,name,age);///////////
// Parent.apply(this,[name,age]);/////////// 都可
Parent.apply(this,arguments);///////////
this.sayGrade=function(){
alert("My grade is "+this.grade);
}
// this.sayHi=function(){
// alert("Hi, my name is "+this.name+", my age is "+this.age+",My grade is "+this.grade);
// }
}
var chi=new Child("小明","10","5");
chi.sayHi();
chi.sayGrade();
</script>
</body>
以上就是本文的全部?jī)?nèi)容,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作能帶來(lái)一定的幫助,同時(shí)也希望多多支持腳本之家!
相關(guān)文章
event.X和event.clientX的區(qū)別分析
解釋一下event.X和event.clientX有什么區(qū)別?event.clientX返回事件發(fā)生時(shí),mouse相對(duì)于客戶(hù)窗口的X坐標(biāo) event.X也一樣但是如果設(shè)置事件對(duì)象的定位屬性值為relative2011-10-10
JS實(shí)現(xiàn)不用中間變量temp 實(shí)現(xiàn)兩個(gè)變量值得交換方法
這篇文章主要介紹了在JS中 實(shí)現(xiàn)不用中間變量temp 實(shí)現(xiàn)兩個(gè)變量值得交換 ,需要的朋友可以參考下2018-02-02
前端如何用post的方式進(jìn)行eventSource請(qǐng)求
這篇文章主要給大家介紹了關(guān)于前端如何用post的方式進(jìn)行eventSource請(qǐng)求的相關(guān)資料,文中通過(guò)實(shí)例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2023-04-04
JS實(shí)現(xiàn)的打字機(jī)效果完整實(shí)例
這篇文章主要介紹了JS實(shí)現(xiàn)的打字機(jī)效果,結(jié)合完整實(shí)例形式分析了javascript定時(shí)觸發(fā)自定義函數(shù)模擬打字輸出效果的相關(guān)實(shí)現(xiàn)技巧,需要的朋友可以參考下2016-06-06
Postman無(wú)法正常返回結(jié)果問(wèn)題解決
這篇文章主要介紹了Postman無(wú)法正常返回結(jié)果問(wèn)題解決,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-08-08

