淺析2種JavaScript繼承方式
js繼承方法最主要的是2種,一種是通過原型的方式,一種是通過借用call&apply的構(gòu)造函數(shù)方式。
1.原型(prototype):
function Body(name,age){// 創(chuàng)建一個Body類 this.name = name;// 賦予基礎(chǔ)屬性name、age this.age = age; } Body.prototype.sayName =function() {// 給原型定義一個sayName的方法 console.log(this.name); } var a = new Body('wutao','10');//創(chuàng)建一個Body的實(shí)例對象 function Another(){} Another.prototype = new Body('www');//將Body實(shí)例對象給新創(chuàng)建的子類(Another)的prototype屬性,這樣,Another就擁有了Body的屬性和方法 var b = new Another();//創(chuàng)建Another子類的實(shí)例 Another.prototype.sex ="mail";//定義子類的屬性及方法 Another.prototype.saySex = function(){ console.log(this.sex); } a.sayName();//wutao b.sayName();//www 實(shí)例b擁有父類Body的方法sayName b.saySex();//mail 實(shí)例b擁有自己定義的方法saySex
2.借用構(gòu)造函數(shù)(call&apply),也可以理解為組合式繼承
call:
function Person(name){ this.name = name; this.sayHello = function(){ console.log(this.name); } } function Son(name,age){ Person.call(this,name,age);//call用法:將this指針指向父類構(gòu)造函數(shù),并依次傳入?yún)?shù),使其擁有父類的屬性和方法 this.age = age; this.sayFunc = function(){ console.log(this.name+"-"+this.age); } } var a = new Person('wutao'); var b = new Son("wwwwww",22); a.sayHello();//wutao b.sayHello();//wwwwww; 通過call繼承來的父類Person的方法sayHello b.sayFunc();//wwwwww-22
apply:
function Person(name){ this.name = name; this.sayHello = function(){ console.log(this.name); } } function Son(name,age){ Person.apply(this,[name,age]);//apply用法:類似call,將this指針指向父類構(gòu)造函數(shù),并傳入一個由參數(shù)組成的數(shù)組參數(shù),使其擁有父類的屬性和方法 this.age = age; this.sayFunc = function(){ console.log(this.name+"-"+this.age); } } var a = new Person('wutao'); var b = new Son("ttt",222); a.sayHello();//wutao b.sayHello();//ttt;通過apply繼承來的父類Person的方法sayHello b.sayFunc();//ttt-222
js最主要的繼承方法就這2種,當(dāng)然,還有幾種繼承方法,但是有些繼承方式在創(chuàng)建了實(shí)例之后,修改實(shí)例方法和屬性會直接修改原型的方法和屬性,那這樣的繼承就顯得意義不大了,除非是業(yè)務(wù)有類似的需求才會去用到。
以上就是關(guān)于JavaScript繼承方式的詳細(xì)介紹,希望對大家的學(xué)習(xí)有所幫助。
相關(guān)文章
JavaScript中判斷為整數(shù)的多種方式及保留兩位小數(shù)的方法
這篇文章主要介紹了JavaScript中判斷為整數(shù)的多種方式,以及保留兩位小數(shù)的方法,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),具有一定的參考借鑒價值,需要的朋友可以參考下2019-09-09