js的三種繼承方式詳解
更新時間:2017年01月21日 08:22:19 作者:hahaxiaotianxia
本文主要介紹了js的三種繼承方式。具有一定的參考價值,下面跟著小編一起來看下吧
1.js原型(prototype)實現(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ù)實現(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實現(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>
以上就是本文的全部內(nèi)容,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作能帶來一定的幫助,同時也希望多多支持腳本之家!
相關(guān)文章
event.X和event.clientX的區(qū)別分析
解釋一下event.X和event.clientX有什么區(qū)別?event.clientX返回事件發(fā)生時,mouse相對于客戶窗口的X坐標(biāo) event.X也一樣但是如果設(shè)置事件對象的定位屬性值為relative2011-10-10
JS實現(xiàn)不用中間變量temp 實現(xiàn)兩個變量值得交換方法
這篇文章主要介紹了在JS中 實現(xiàn)不用中間變量temp 實現(xiàn)兩個變量值得交換 ,需要的朋友可以參考下2018-02-02

