js繼承方法最主要的是2種,一種是通過(guò)原型的方式,一種是通過(guò)借用call&apply的構(gòu)造函數(shù)方式。
1.原型(prototype):
function Body(name,age){// 創(chuàng)建一個(gè)Body類(lèi) this.name = name;// 賦予基礎(chǔ)屬性name、age this.age = age;}Body.prototype.sayName =function() {// 給原型定義一個(gè)sayName的方法 console.log(this.name);}var a = new Body('wutao','10');//創(chuàng)建一個(gè)Body的實(shí)例對(duì)象function Another(){}Another.prototype = new Body('www');//將Body實(shí)例對(duì)象給新創(chuàng)建的子類(lèi)(Another)的prototype屬性,這樣,Another就擁有了Body的屬性和方法var b = new Another();//創(chuàng)建Another子類(lèi)的實(shí)例Another.prototype.sex ="mail";//定義子類(lèi)的屬性及方法Another.prototype.saySex = function(){ console.log(this.sex);}a.sayName();//wutaob.sayName();//www 實(shí)例b擁有父類(lèi)Body的方法sayNameb.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指針指向父類(lèi)構(gòu)造函數(shù),并依次傳入?yún)?shù),使其擁有父類(lèi)的屬性和方法 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();//wutaob.sayHello();//wwwwww; 通過(guò)call繼承來(lái)的父類(lèi)Person的方法sayHellob.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用法:類(lèi)似call,將this指針指向父類(lèi)構(gòu)造函數(shù),并傳入一個(gè)由參數(shù)組成的數(shù)組參數(shù),使其擁有父類(lèi)的屬性和方法 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();//wutaob.sayHello();//ttt;通過(guò)apply繼承來(lái)的父類(lèi)Person的方法sayHellob.sayFunc();//ttt-222
js最主要的繼承方法就這2種,當(dāng)然,還有幾種繼承方法,但是有些繼承方式在創(chuàng)建了實(shí)例之后,修改實(shí)例方法和屬性會(huì)直接修改原型的方法和屬性,那這樣的繼承就顯得意義不大了,除非是業(yè)務(wù)有類(lèi)似的需求才會(huì)去用到。
以上就是關(guān)于JavaScript繼承方式的詳細(xì)介紹,希望對(duì)大家的學(xué)習(xí)有所幫助。