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