您好,登錄后才能下訂單哦!
這篇文章主要介紹js中有哪三種繼承方式,文中介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們一定要看完!
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>
以上是“js中有哪三種繼承方式”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對(duì)大家有幫助,更多相關(guān)知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀(guān)點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。