avaScript對每個創(chuàng)建的對象都會設(shè)置一個原型族操,指向它的原型對象。
當(dāng)我們用obj.xxx訪問一個對象的屬性時比被,JavaScript引擎先在當(dāng)前對象上查找該屬性色难,如果沒有找到,就到其原型對象上找等缀,如果還沒有找到枷莉,就一直上溯到Object.prototype對象,最后尺迂,如果還沒有找到笤妙,就只能返回undefined。
例如枪狂,創(chuàng)建一個Array對象:
var arr = [1, 2, 3];
其原型鏈?zhǔn)牵?/p>
arr ----> Array.prototype ----> Object.prototype ----> null
Array.prototype定義了indexOf()危喉、shift()等方法,因此你可以在所有的Array對象上直接調(diào)用這些方法州疾。
當(dāng)我們創(chuàng)建一個函數(shù)時:
function foo() {
return 0;
}
函數(shù)也是一個對象辜限,它的原型鏈?zhǔn)牵?/p>
foo ----> Function.prototype ----> Object.prototype ----> null
由于Function.prototype定義了apply()等方法,因此严蓖,所有函數(shù)都可以調(diào)用apply()方法薄嫡。
很容易想到氧急,如果原型鏈很長,那么訪問一個對象的屬性就會因為花更多的時間查找而變得更慢毫深,因此要注意不要把原型鏈搞得太長吩坝。
構(gòu)造函數(shù)
除了直接用{ ... }創(chuàng)建一個對象外,JavaScript還可以用一種構(gòu)造函數(shù)的方法來創(chuàng)建對象哑蔫。它的用法是钉寝,先定義一個構(gòu)造函數(shù):
function Student(name) {
this.name = name;
this.hello = function () {
alert('Hello, ' + this.name + '!');
}
}
你會問,咦闸迷,這不是一個普通函數(shù)嗎?
這確實是一個普通函數(shù)嵌纲,但是在JavaScript中,可以用關(guān)鍵字new來調(diào)用這個函數(shù)腥沽,并返回一個對象:
var xiaoming = new Student('小明');
xiaoming.name; // '小明'
xiaoming.hello(); // Hello, 小明!
注意逮走,如果不寫new,這就是一個普通函數(shù)今阳,它返回undefined师溅。但是,如果寫了new盾舌,它就變成了一個構(gòu)造函數(shù)墓臭,它綁定的this指向新創(chuàng)建的對象,并默認(rèn)返回this妖谴,也就是說起便,不需要在最后寫return this;
新創(chuàng)建的xiaoming的原型鏈?zhǔn)牵?/p>
xiaoming ----> Student.prototype ----> Object.prototype ----> null
也就是說,xiaoming的原型指向函數(shù)Student的原型窖维。如果你又創(chuàng)建了xiaohong、xiaojun妙痹,那么這些對象的原型與xiaoming是一樣的:
xiaoming ↘
xiaohong -→Student.prototype ----> Object.prototype ----> null
xiaojun ↗
用new Student()創(chuàng)建的對象還從原型上獲得了一個constructor屬性铸史,它指向函數(shù)Student本身:
xiaoming.constructor === Student.prototype.constructor; // true
Student.prototype.constructor === Student; // true
Object.getPrototypeOf(xiaoming) === Student.prototype; // true
xiaoming instanceof Student; // true
看暈了吧?用一張圖來表示這些亂七八糟的關(guān)系就是:
紅色箭頭是原型鏈言询。注意粒没,Student.prototype指向的對象就是xiaoming、xiaohong的原型對象转培,這個原型對象自己還有個屬性constructor耿芹,指向Student函數(shù)本身崭篡。
另外,函數(shù)Student恰好有個屬性prototype指向xiaoming吧秕、xiaohong的原型對象琉闪,但是xiaoming、xiaohong這些對象可沒有prototype這個屬性砸彬,不過可以用__proto__這個非標(biāo)準(zhǔn)用法來查看颠毙。
現(xiàn)在我們就認(rèn)為xiaoming斯入、xiaohong這些對象“繼承”自Student。
不過還有一個小問題蛀蜜,注意觀察:
xiaoming.name; // '小明'
xiaohong.name; // '小紅'
xiaoming.hello; // function: Student.hello()
xiaohong.hello; // function: Student.hello()
xiaoming.hello === xiaohong.hello; // false
xiaoming和xiaohong各自的name不同刻两,這是對的,否則我們無法區(qū)分誰是誰了滴某。
xiaoming和xiaohong各自的hello是一個函數(shù)磅摹,但它們是兩個不同的函數(shù),雖然函數(shù)名稱和代碼都是相同的!
如果我們通過new Student()創(chuàng)建了很多對象霎奢,這些對象的hello函數(shù)實際上只需要共享同一個函數(shù)就可以了户誓,這樣可以節(jié)省很多內(nèi)存。
要讓創(chuàng)建的對象共享一個hello函數(shù)椰憋,根據(jù)對象的屬性查找原則厅克,我們只要把hello函數(shù)移動到xiaoming、xiaohong這些對象共同的原型上就可以了橙依,也就是Student.prototype:
修改代碼如下:
function Student(name) {
this.name = name;
}
Student.prototype.hello = function () {
alert('Hello, ' + this.name + '!');
};
用new創(chuàng)建基于原型的JavaScript的對象就是這么簡單!
忘記寫new怎么辦
如果一個函數(shù)被定義為用于創(chuàng)建對象的構(gòu)造函數(shù)证舟,但是調(diào)用時忘記了寫new怎么辦?
在strict模式下,this.name = name將報錯窗骑,因為this綁定為undefined女责,在非strict模式下,this.name = name不報錯创译,因為this綁定為window抵知,于是無意間創(chuàng)建了全局變量name,并且返回undefined软族,這個結(jié)果更糟糕刷喜。
所以,調(diào)用構(gòu)造函數(shù)千萬不要忘記寫new立砸。為了區(qū)分普通函數(shù)和構(gòu)造函數(shù)掖疮,按照約定,構(gòu)造函數(shù)首字母應(yīng)當(dāng)大寫颗祝,而普通函數(shù)首字母應(yīng)當(dāng)小寫浊闪,這樣,一些語法檢查工具如jslint將可以幫你檢測到漏寫的new螺戳。
最后搁宾,我們還可以編寫一個createStudent()函數(shù),在內(nèi)部封裝所有的new操作倔幼。一個常用的編程模式像這樣:
function Student(props) {
this.name = props.name || '匿名'; // 默認(rèn)值為'匿名'
this.grade = props.grade || 1; // 默認(rèn)值為1
}
Student.prototype.hello = function () {
alert('Hello, ' + this.name + '!');
};
function createStudent(props) {
return new Student(props || {})
}
這個createStudent()函數(shù)有幾個巨大的優(yōu)點(diǎn):一是不需要new來調(diào)用盖腿,二是參數(shù)非常靈活,可以不傳凤藏,也可以這么傳:
var xiaoming = createStudent({
name: '小明'
});
xiaoming.grade; // 1
如果創(chuàng)建的對象有很多屬性奸忽,我們只需要傳遞需要的某些屬性堕伪,剩下的屬性可以用默認(rèn)值。由于參數(shù)是一個Object栗菜,我們無需記憶參數(shù)的順序欠雌。如果恰好從JSON拿到了一個對象,就可以直接創(chuàng)建出xiaoming疙筹。
繼承
在傳統(tǒng)的基于Class的語言如Java富俄、C++中,繼承的本質(zhì)是擴(kuò)展一個已有的Class而咆,并生成新的Subclass霍比。
由于這類語言嚴(yán)格區(qū)分類和實例,繼承實際上是類型的擴(kuò)展暴备。但是悠瞬,JavaScript由于采用原型繼承,我們無法直接擴(kuò)展一個Class涯捻,因為根本不存在Class這種類型浅妆。
但是辦法還是有的。我們先回顧Student構(gòu)造函數(shù):
function Student(props) {
this.name = props.name || 'Unnamed';
}
Student.prototype.hello = function () {
alert('Hello, ' + this.name + '!');
}
以及Student的原型鏈:
現(xiàn)在障癌,我們要基于Student擴(kuò)展出PrimaryStudent凌外,可以先定義出PrimaryStudent:
function PrimaryStudent(props) {
// 調(diào)用Student構(gòu)造函數(shù),綁定this變量:
Student.call(this, props);
this.grade = props.grade || 1;
}
但是涛浙,調(diào)用了Student構(gòu)造函數(shù)不等于繼承了Student康辑,PrimaryStudent創(chuàng)建的對象的原型是:
new PrimaryStudent() ----> PrimaryStudent.prototype ----> Object.prototype ----> null
必須想辦法把原型鏈修改為:
new PrimaryStudent() ----> PrimaryStudent.prototype ----> Student.prototype ----> Object.prototype ----> null
這樣,原型鏈對了轿亮,繼承關(guān)系就對了疮薇。新的基于PrimaryStudent創(chuàng)建的對象不但能調(diào)用PrimaryStudent.prototype定義的方法,也可以調(diào)用Student.prototype定義的方法我注。
如果你想用最簡單粗暴的方法這么干:
PrimaryStudent.prototype = Student.prototype;
是不行的!如果這樣的話惦辛,PrimaryStudent和Student共享一個原型對象,那還要定義PrimaryStudent干啥?
我們必須借助一個中間對象來實現(xiàn)正確的原型鏈仓手,這個中間對象的原型要指向Student.prototype。為了實現(xiàn)這一點(diǎn)玻淑,參考道爺(就是發(fā)明JSON的那個道格拉斯)的代碼嗽冒,中間對象可以用一個空函數(shù)F來實現(xiàn):
// PrimaryStudent構(gòu)造函數(shù):
function PrimaryStudent(props) {
Student.call(this, props);
this.grade = props.grade || 1;
}
// 空函數(shù)F:
function F() {
}
// 把F的原型指向Student.prototype:
F.prototype = Student.prototype;
// 把PrimaryStudent的原型指向一個新的F對象,F(xiàn)對象的原型正好指向Student.prototype:
PrimaryStudent.prototype = new F();
// 把PrimaryStudent原型的構(gòu)造函數(shù)修復(fù)為PrimaryStudent:
PrimaryStudent.prototype.constructor = PrimaryStudent;
// 繼續(xù)在PrimaryStudent原型(就是new F()對象)上定義方法:
PrimaryStudent.prototype.getGrade = function () {
return this.grade;
};
// 創(chuàng)建xiaoming:
var xiaoming = new PrimaryStudent({
name: '小明',
grade: 2
});
xiaoming.name; // '小明'
xiaoming.grade; // 2
// 驗證原型:
xiaoming.__proto__ === PrimaryStudent.prototype; // true
xiaoming.__proto__.__proto__ === Student.prototype; // true
// 驗證繼承關(guān)系:
xiaoming instanceof PrimaryStudent; // true
xiaoming instanceof Student; // true
用一張圖來表示新的原型鏈:
注意补履,函數(shù)F僅用于橋接添坊,我們僅創(chuàng)建了一個new F()實例,而且箫锤,沒有改變原有的Student定義的原型鏈贬蛙。
如果把繼承這個動作用一個inherits()函數(shù)封裝起來雨女,還可以隱藏F的定義,并簡化代碼:
function inherits(Child, Parent) {
var F = function () {};
F.prototype = Parent.prototype;
Child.prototype = new F();
Child.prototype.constructor = Child;
}
這個inherits()函數(shù)可以復(fù)用:
function Student(props) {
this.name = props.name || 'Unnamed';
}
Student.prototype.hello = function () {
alert('Hello, ' + this.name + '!');
}
function PrimaryStudent(props) {
Student.call(this, props);
this.grade = props.grade || 1;
}
// 實現(xiàn)原型繼承鏈:
inherits(PrimaryStudent, Student);
// 綁定其他方法到PrimaryStudent原型:
PrimaryStudent.prototype.getGrade = function () {
return this.grade;
};
小結(jié)
JavaScript的原型繼承實現(xiàn)方式就是:
定義新的構(gòu)造函數(shù)阳准,并在內(nèi)部用call()調(diào)用希望“繼承”的構(gòu)造函數(shù)氛堕,并綁定this;
借助中間函數(shù)F實現(xiàn)原型鏈繼承,最好通過封裝的inherits函數(shù)完成;
繼續(xù)在新的構(gòu)造函數(shù)的原型上定義新方法野蝇。
ES6的class繼承
新的關(guān)鍵字class從ES6開始正式被引入到JavaScript中讼稚。class的目的就是讓定義類更簡單。
我們先回顧用函數(shù)實現(xiàn)Student的方法:
function Student(name) {
this.name = name;
}
Student.prototype.hello = function () {
alert('Hello, ' + this.name + '!');
}
如果用新的class關(guān)鍵字來編寫Student绕沈,可以這樣寫:
class Student {
constructor(name) {
this.name = name;
}
hello() {
alert('Hello, ' + this.name + '!');
}
}
比較一下就可以發(fā)現(xiàn)锐想,class的定義包含了構(gòu)造函數(shù)constructor和定義在原型對象上的函數(shù)hello()(注意沒有function關(guān)鍵字),這樣就避免了Student.prototype.hello = function () {...}這樣分散的代碼乍狐。
最后赠摇,創(chuàng)建一個Student對象代碼和前面章節(jié)完全一樣:
var xiaoming = new Student('小明');
xiaoming.hello();
class繼承
用class定義對象的另一個巨大的好處是繼承更方便了。想一想我們從Student派生一個PrimaryStudent需要編寫的代碼量∏瞅剑現(xiàn)在藕帜,原型繼承的中間對象,原型對象的構(gòu)造函數(shù)等等都不需要考慮了掘鄙,直接通過extends來實現(xiàn):
class PrimaryStudent extends Student {
constructor(name, grade) {
super(name); // 記得用super調(diào)用父類的構(gòu)造方法!
this.grade = grade;
}
myGrade() {
alert('I am at grade ' + this.grade);
}
}
注意PrimaryStudent的定義也是class關(guān)鍵字實現(xiàn)的耘戚,而extends則表示原型鏈對象來自Student。子類的構(gòu)造函數(shù)可能會與父類不太相同操漠,例如收津,PrimaryStudent需要name和grade兩個參數(shù),并且需要通過super(name)來調(diào)用父類的構(gòu)造函數(shù)浊伙,否則父類的name屬性無法正常初始化撞秋。
PrimaryStudent已經(jīng)自動獲得了父類Student的hello方法,我們又在子類中定義了新的myGrade方法嚣鄙。
ES6引入的class和原有的JavaScript原型繼承有什么區(qū)別呢?實際上它們沒有任何區(qū)別吻贿,class的作用就是讓JavaScript引擎去實現(xiàn)原來需要我們自己編寫的原型鏈代碼。簡而言之哑子,用class的好處就是極大地簡化了原型鏈代碼舅列。