您好,登錄后才能下訂單哦!
這篇文章主要介紹js中有哪三種繼承方式,文中介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們一定要看完!
1.js原型(prototype)實現繼承
代碼如下
<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.構造函數實現繼承
代碼如下:
<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實現繼承 -----很方便!
代碼如下:
<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中有哪三種繼承方式”這篇文章的所有內容,感謝各位的閱讀!希望分享的內容對大家有幫助,更多相關知識,歡迎關注億速云行業資訊頻道!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。