作為一門(mén)面向?qū)ο蟮恼Z(yǔ)言散址,JavaScript并沒(méi)有“父類(lèi)”與“子類(lèi)”的概念幢痘,也沒(méi)有像java提供extends關(guān)鍵字瀑踢,c++中直接提供繼承方法等那樣直接進(jìn)行繼承辨宠。然而繼承在面向?qū)ο蟮恼Z(yǔ)言中的重要性不言而喻,所以琳省,下述將簡(jiǎn)要探討一下迎吵,JavaScript中的幾種常用的繼承方法。
首先针贬,我們需要定義一個(gè)父類(lèi):
function Parent(username)
{
this.username = username;
this.sayHello = function()
{
return this.username;
}
}
沒(méi)有現(xiàn)成的繼承方法的情況下击费,JavaScript學(xué)習(xí)者們通過(guò)對(duì)JavaScript的理解總結(jié)出5中常見(jiàn)的實(shí)用的繼承方法:
- 對(duì)象冒充
- call方法
- apply方法
- 原型鏈方式
- 混合方式(推薦)
1、對(duì)象冒充
顧名思義坚踩,子類(lèi)通過(guò)冒充父類(lèi)荡灾,從而獲得父類(lèi)的屬性和方法瓤狐,其中最重要的是下列三行代碼
this.method = Parent;
this.method (username);
delete this.method;
以上的this均指代的是“子代”的實(shí)例瞬铸,第一行代碼為定義一個(gè)成員方法,即把函數(shù)Parent作為“子代”的成員方法础锐;第二行為執(zhí)行成員方法嗓节,該方法把Parent的屬性和方法添加給了“子代”的實(shí)例;第三行為刪除該方法皆警,因?yàn)榉椒ㄒ呀?jīng)執(zhí)行拦宣,“父代”的屬性與方法已經(jīng)獲得。刪不刪都一樣信姓。
function Child(username,password)
{
this.method = Parent;
this.method(username);
delete this.method;
this.password = password;
this.sayWorld = function()
{
return this.password;
}
}
var parent = new Parent("zhangsan");
var child = new Child("lisi","123");
2鸵隧、call方法方式
call方法是Function對(duì)象中的方法,因此我們定義的每個(gè)函數(shù)都有該方法意推《固保可以通過(guò)調(diào)用函數(shù)名來(lái)調(diào)用call方法call方法的第1個(gè)參數(shù)會(huì)被傳遞給Parent函數(shù)中的this,從第2個(gè)參數(shù)開(kāi)始菊值,逐一賦值給Parent函數(shù)中的參數(shù)外驱。
function Child(username,password)
{
Parent.call(this,username);
this.password = password;
this.sayWorld = function()
{
return this.password;
}
}
var parent = new Parent("zhangsan");
var child = new Child("lisi","123");
Parent.call(this,username) 此處的this為子對(duì)象的this育灸,傳遞給父對(duì)象,則function Parent(username)中的this全部為子對(duì)象的this昵宇,即完成了繼承磅崭。
3、apply方式方法
apply方式與call方法結(jié)構(gòu)上相近瓦哎,唯一的區(qū)別就是apply中的參數(shù)傳遞規(guī)定的是數(shù)組形式砸喻,不用像call方法那樣一個(gè)一個(gè)地寫(xiě)。
function Child(username,password)
{
Parent.apply(this,new Array(username));
this.password = password;
this.sayWorld = function()
{
return this.password;
}
}
4杭煎、原型鏈方式
原型鏈方式與對(duì)象冒充的原理一樣恩够,通過(guò)將Parent函數(shù)賦給“子代”作為其成員方法從而實(shí)現(xiàn)繼承。然而羡铲,單純的原型鏈方式有其固有的缺陷蜂桶,與使用原型鏈方式構(gòu)建對(duì)象時(shí)一樣,它無(wú)法給構(gòu)造函數(shù)傳遞參數(shù)也切。
function Parent()
{}
Parent.prototype.username = "zhangsan";
Parent.prototype.sayHello = function()
{
return this.username;
}
function Child()
{}
Child.prototype = new Parent();
Child.prototype.password = "123";
Child.prototype.sayWorld = function()
{
return this.password;
}
var child = new Child();
child.sayHello();
child.sayWorld();
5扑媚、混合方式
Parent.call()進(jìn)行屬性的繼承,Child.prototype=new Parent()進(jìn)行方法的繼承雷恃。實(shí)現(xiàn)方法共享疆股,屬性私有。
function Parent(username)
{
this.username=username;
}
Parent.prototype.sayHello = function()
{
return this.username;
}
function Child(username,password)
{
Parent.call(this,username);
this.password = password;
}
Child.prototype = new Parent();
Child.prototype.sayWorld = function()
{
return this.password;
}
var child=new Child("zhangsan","123");
child.sayHello();
child.sayWorld();