淺析2種JavaScript繼承方式
更新時間:2015年12月04日 08:30:38 作者:我的頭很光
這篇文章主要介紹了2種JavaScript主要繼承方式,一種是通過原型的方式,一種是通過借用call&apply的構(gòu)造函數(shù)方式,感興趣的小伙伴們可以參考一下
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的實例對象
function Another(){}
Another.prototype = new Body('www');//將Body實例對象給新創(chuàng)建的子類(Another)的prototype屬性,這樣,Another就擁有了Body的屬性和方法
var b = new Another();//創(chuàng)建Another子類的實例
Another.prototype.sex ="mail";//定義子類的屬性及方法
Another.prototype.saySex = function(){
console.log(this.sex);
}
a.sayName();//wutao
b.sayName();//www 實例b擁有父類Body的方法sayName
b.saySex();//mail 實例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種,當然,還有幾種繼承方法,但是有些繼承方式在創(chuàng)建了實例之后,修改實例方法和屬性會直接修改原型的方法和屬性,那這樣的繼承就顯得意義不大了,除非是業(yè)務有類似的需求才會去用到。
以上就是關(guān)于JavaScript繼承方式的詳細介紹,希望對大家的學習有所幫助。
相關(guān)文章
JavaScript 模塊的循環(huán)加載實現(xiàn)方法
本文介紹JavaScript語言如何處理"循環(huán)加載"。目前,最常見的兩種模塊格式CommonJS和ES6,處理方法是不一樣的,返回的結(jié)果也不一樣2015-12-12
JavaScript常見數(shù)組方法之如何轉(zhuǎn)置矩陣
這篇文章主要給大家介紹了關(guān)于JavaScript常見數(shù)組方法之如何轉(zhuǎn)置矩陣的相關(guān)資料,文中通過實例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2022-03-03

