您現在的位置是:首頁 >綜合 > 2023-08-29 20:16:07 來源:
js的繼承的6種方法(js繼承的幾種方式)
大家好,我是小夏,我來為大家解答以上問題。js的繼承的6種方法,js繼承的幾種方式很多人還不知道,現在讓我們一起來看看吧!
1、繼承的方式一共有三種:<br>一、原型繼承<br>通過prototype???來實現繼承。
2、<br>function?Person(name,age)?{????this.name=name;????this.age=age;<br>}<br><br>Person.prototype.sayHello=function(){<br>alert?('使用原型得到Name:'?+?this.name);<br><br>}????var?per?=?new?Person("馬小倩",21);<br>per.sayHello();//輸出:使用原型得到Name:馬小倩?<br><br>function?Student(){}<br><br>Student.prototype=new?Person("洪如彤",21);??//實現原型繼承<br><br>var??stu?=?new?Student();<br><br>Student.prototype.grade=5;??<br><br>Student.prototype.intr=function(){<br>alert(this.grade);<br>}??<br><br>stu.sayHello();//輸出:使用原型得到Name:洪如彤<br>stu.intr();//輸出:5??<br><br>二、構造函數實現繼承<br>function?Person(name,age)?{????this.name=name;????this.age=age;<br>}<br><br>Person.prototype.sayHello=function(){<br>alert?('使用原型得到Name:'?+?this.name);<br><br>}????var?per?=?new?Person("馬小倩",21);<br>per.sayHello();//輸出:使用原型得到Name:馬小倩<br><br>三、??通過call、apply??實現繼承。
本文到此講解完畢了,希望對大家有幫助。