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.構造函數(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)容對大家的學習或者工作能帶來一定的幫助,同時也希望多多支持腳本之家!
相關文章
解決idea開發(fā)遇到javascript動態(tài)添加html元素時中文亂碼的問題
這篇文章主要介紹了解決idea開發(fā)遇到javascript動態(tài)添加html元素時中文亂碼的問題,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-09-09
javascript 控制input只允許輸入的各種指定內(nèi)容
這篇文章主要介紹了通過javascript控制input只允許輸入的各種指定內(nèi)容,需要的朋友可以參考下2014-06-06
JavaScript使用SpreadJS創(chuàng)建Excel查看器
在現(xiàn)代的Web應用開發(fā)中,Excel文件的處理和展示是一項常見的需求,小編今天將為大家展示如何借助SpreadJS來創(chuàng)建一個Excel查看器,感興趣的小伙伴可以了解下2023-12-12
解決bootstrap-select 動態(tài)加載數(shù)據(jù)不顯示的問題
今天小編就為大家分享一篇解決bootstrap-select 動態(tài)加載數(shù)據(jù)不顯示的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-08-08
微信小程序全局變量GLOBALDATA的定義和調(diào)用過程解析
這篇文章主要介紹了微信小程序全局變量GLOBALDATA的定義和調(diào)用過程解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2019-09-09
JS中split()用法(將字符串按指定符號分割成數(shù)組)
這篇文章主要介紹了JS中split()用法(將字符串按指定符號分割成數(shù)組)的相關資料,非常不錯具有參考借鑒價值,需要的朋友可以參考下2016-10-10

