JavaScript對每一個建立的對象都會設置一個原型,指向它的原型對象。編程
當咱們用obj.xxx
訪問一個對象的屬性時,JavaScript引擎先在當前對象上查找該屬性,若是沒有找到,就到其原型對象上找,若是尚未找到,就一直上溯到Object.prototype
對象,最後,若是尚未找到,就只能返回undefined
。瀏覽器
例如,建立一個Array
對象:babel
var arr = [1, 2, 3]; // 其原型鏈是: arr ----> Array.prototype ----> Object.prototype ----> null
Array.prototype
定義了indexOf()
、shift()
等方法,所以你能夠在全部的Array
對象上直接調用這些方法。app
函數也是一個對象,它的原型鏈是:函數
fun ----> Function.prototype ----> Object.prototype ----> null
因爲Function.prototype
定義了apply()
等方法,所以,全部函數均可以調用apply()
方法。工具
很容易想到,若是原型鏈很長,那麼訪問一個對象的屬性就會由於花更多的時間查找而變得更慢,所以要注意不要把原型鏈搞得太長。this
除了直接用{ ... }
建立一個對象外,JavaScript還能夠用一種構造函數的方法來建立對象。它的用法是,先定義一個構造函數:spa
function Student(name) { this.name = name; this.hello = function () { alert('Hello, ' + this.name + '!'); } }
和一個普通函數同樣,可是在JavaScript中,能夠用關鍵字new
來調用這個函數,並返回一個對象:prototype
var xiaoming = new Student('小明'); xiaoming.name; // '小明' xiaoming.hello(); // Hello, 小明!
注意,若是不寫new
,這就是一個普通函數,它返回undefined
。可是,若是寫了new
,它就變成了一個構造函數,它綁定的this
指向新建立的對象,並默認返回this
,也就是說,不須要在最後寫return this;
。code
新建立的xiaoming
的原型鏈是:
xiaoming ----> Student.prototype ----> Object.prototype ----> null
也就是說,xiaoming
的原型指向函數Student
的原型。若是你又建立了xiaohong
、xiaojun
,那麼這些對象的原型與xiaoming
是同樣的:
xiaoming ↘ xiaohong -→ Student.prototype ----> Object.prototype ---->null xiaojun ↗
用new Student()
建立的對象還從原型上得到了一個constructor
屬性,它指向函數Student
自己:
xiaoming.constructor === Student.prototype.constructor; // true Student.prototype.constructor === Student; // true Object.getPrototypeOf(xiaoming) === Student.prototype; // true xiaoming instanceof Student; // true
用一張圖來表示這些亂七八糟的關係就是:
紅色箭頭是原型鏈。注意,Student.prototype
指向的對象就是xiaoming
、xiaohong
的原型對象,這個原型對象本身還有個屬性constructor
,指向Student
函數自己。
另外,函數Student
剛好有個屬性prototype
指向xiaoming
、xiaohong
的原型對象,可是xiaoming
、xiaohong
這些對象可沒有prototype
這個屬性,不過能夠用__proto__
這個非標準用法來查看。
如今咱們就認爲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
不一樣,這是對的,不然咱們沒法區分誰是誰了。
xiaoming
和xiaohong
各自的hello
是一個函數,但它們是兩個不一樣的函數,雖然函數名稱和代碼都是相同的!
若是咱們經過new Student()
建立了不少對象,這些對象的hello
函數實際上只須要共享同一個函數就能夠了,這樣能夠節省不少內存。
要讓建立的對象共享一個hello
函數,根據對象的屬性查找原則,咱們只要把hello
函數移動到xiaoming
、xiaohong
這些對象共同的原型上就能夠了,也就是Student.prototype
:
修改代碼以下:
function Student(name) { this.name = name; } Student.prototype.hello = function () { alert('Hello, ' + this.name + '!'); };
用new
建立基於原型的JavaScript的對象就是這麼簡單!
若是一個函數被定義爲用於建立對象的構造函數,可是調用時忘記了寫new
怎麼辦?
在strict模式下,this.name = name
將報錯,由於this
綁定爲undefined
,在非strict模式下,this.name = name
不報錯,由於this
綁定爲window
,因而無心間建立了全局變量name
,而且返回undefined
,這個結果更糟糕。
因此,調用構造函數千萬不要忘記寫new
。爲了區分普通函數和構造函數,按照約定,構造函數首字母應當大寫,而普通函數首字母應當小寫,這樣,一些語法檢查工具如jslint將能夠幫你檢測到漏寫的new
。
最後,咱們還能夠編寫一個createStudent()
函數,在內部封裝全部的new
操做。一個經常使用的編程模式像這樣:
function Student(props) { this.name = props.name || '匿名'; // 默認值爲'匿名' this.grade = props.grade || 1; // 默認值爲1 } Student.prototype.hello = function () { alert('Hello, ' + this.name + '!'); };
function createStudent(props) { return new Student(props || {}); }
這個createStudent()
函數有幾個巨大的優勢:一是不須要new
來調用,二是參數很是靈活,能夠不傳,也能夠這麼傳:
var xiaoming = createStudent({name: '小明'}); xiaoming.grade; // 1
若是建立的對象有不少屬性,咱們只須要傳遞須要的某些屬性,剩下的屬性能夠用默認值。因爲參數是一個Object,咱們無需記憶參數的順序。若是剛好從JSON
拿到了一個對象,就能夠直接建立出xiaoming
。
在傳統的基於Class的語言如Java、C++中,繼承的本質是擴展一個已有的Class,並生成新的Subclass。
因爲這類語言嚴格區分類和實例,繼承其實是類型的擴展。可是,JavaScript因爲採用原型繼承,咱們沒法直接擴展一個Class,由於根本不存在Class這種類型。
可是辦法仍是有的。咱們先回顧Student
構造函數:
function Student(props) { this.name = props.name || 'Unnamed'; } Student.prototype.hello = function () { alert('Hello, ' + this.name + '!'); }
以及Student
的原型鏈:
如今,咱們要基於Student
擴展出PrimaryStudent
,能夠先定義出PrimaryStudent
:
function PrimaryStudent(props) { // 調用Student構造函數,綁定this變量: Student.call(this, props); this.grade = props.grade || 1; }
可是,調用了Student
構造函數不等於繼承了Student
,PrimaryStudent
建立的對象的原型是:
new PrimaryStudent() ----> PrimaryStudent.prototype ----> Object.prototype ----> null
必須想辦法把原型鏈修改成:
new PrimaryStudent() ----> PrimaryStudent.prototype ----> Student.prototype ----> Object.prototype ----> null
這樣,原型鏈對了,繼承關係就對了。新的基於PrimaryStudent
建立的對象不但能調用PrimaryStudent.prototype
定義的方法,也能夠調用Student.prototype
定義的方法。
若是你想用最簡單粗暴的方法這麼幹:
PrimaryStudent.prototype = Student.prototype;
是不行的!若是這樣的話,PrimaryStudent
和Student
共享一個原型對象,那還要定義PrimaryStudent
幹啥?
咱們必須藉助一箇中間對象來實現正確的原型鏈,這個中間對象的原型要指向Student.prototype
。爲了實現這一點,參考道爺(就是發明JSON的那個道格拉斯)的代碼,中間對象能夠用一個空函數F
來實現:
// PrimaryStudent構造函數: function PrimaryStudent(props) { Student.call(this, props); this.grade = props.grade || 1; } // 空函數F: function F() {} // 把F的原型指向Student.prototype: F.prototype = Student.prototype; // 把PrimaryStudent的原型指向一個新的F對象,F對象的原型正好指向Student.prototype: PrimaryStudent.prototype = new F(); // 把PrimaryStudent原型的構造函數修復爲PrimaryStudent: PrimaryStudent.prototype.constructor = PrimaryStudent; // 繼續在PrimaryStudent原型(就是new F()對象)上定義方法: PrimaryStudent.prototype.getGrade = function () { return this.grade; }; // 建立xiaoming: var xiaoming = new PrimaryStudent({ name: '小明', grade: 2}); xiaoming.name; // '小明' xiaoming.grade; // 2 // 驗證原型: xiaoming.__proto__ === PrimaryStudent.prototype; // true xiaoming.__proto__.__proto__ === Student.prototype; // true // 驗證繼承關係: xiaoming instanceof PrimaryStudent; // true xiaoming instanceof Student; // true
用一張圖來表示新的原型鏈:
注意,函數F
僅用於橋接,咱們僅建立了一個new F()
實例,並且,沒有改變原有的Student
定義的原型鏈。
若是把繼承這個動做用一個inherits()
函數封裝起來,還能夠隱藏F
的定義,並簡化代碼:
function inherits(Child, Parent) { var F = function () {}; F.prototype = Parent.prototype; Child.prototype = new F(); Child.prototype.constructor = Child; }
這個inherits()
函數能夠複用:
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; } // 實現原型繼承鏈: inherits(PrimaryStudent, Student); // 綁定其餘方法到PrimaryStudent原型: PrimaryStudent.prototype.getGrade = function () { return this.grade; };
JavaScript的原型繼承實現方式就是:
定義新的構造函數,並在內部用call()
調用但願「繼承」的構造函數,並綁定this
;
藉助中間函數F
實現原型鏈繼承,最好經過封裝的inherits
函數完成;
繼續在新的構造函數的原型上定義新方法。
在上面的章節中咱們看到了JavaScript的對象模型是基於原型實現的,特色是簡單,缺點是理解起來比傳統的類-實例模型要困難,最大的缺點是繼承的實現須要編寫大量代碼,而且須要正確實現原型鏈。
新的關鍵字class
從ES6開始正式被引入到JavaScript中。class
的目的就是讓定義類更簡單。
咱們先回顧用函數實現Student
的方法:
function Student(name) { this.name = name; } Student.prototype.hello = function () { alert('Hello, ' + this.name + '!'); }
若是用新的class
關鍵字來編寫Student
,能夠這樣寫:
class Student { constructor(name) { this.name = name; } hello() { alert('Hello, ' + this.name + '!'); } }
比較一下就能夠發現,class
的定義包含了構造函數constructor
和定義在原型對象上的函數hello()
(注意沒有function
關鍵字),這樣就避免了Student.prototype.hello = function () {...}
這樣分散的代碼。
最後,建立一個Student
對象代碼和前面章節徹底同樣:
var xiaoming = new Student('小明'); xiaoming.hello();
用class
定義對象的另外一個巨大的好處是繼承更方便了。想想咱們從Student
派生一個PrimaryStudent
須要編寫的代碼量。如今,原型繼承的中間對象,原型對象的構造函數等等都不須要考慮了,直接經過extends
來實現:
class PrimaryStudent extends Student { constructor(name, grade) { super(name); // 記得用super調用父類的構造方法! this.grade = grade; } myGrade() { alert('I am at grade ' + this.grade); } hello() { super.hello(); alert('I am at grade ' + this.grade); } }
注意PrimaryStudent
的定義也是class關鍵字實現的,而extends
則表示原型鏈對象來自Student
。子類的構造函數可能會與父類不太相同,例如,PrimaryStudent
須要name
和grade
兩個參數,而且須要經過super(name)
來調用父類的構造函數,不然父類的name
屬性沒法正常初始化。
PrimaryStudent
已經自動得到了父類Student
的hello
方法,咱們又在子類中定義了新的myGrade
方法。
ES6引入的class
和原有的JavaScript原型繼承有什麼區別呢?實際上它們沒有任何區別,class
的做用就是讓JavaScript引擎去實現原來須要咱們本身編寫的原型鏈代碼。簡而言之,用class
的好處就是極大地簡化了原型鏈代碼。
你必定會問,class
這麼好用,能不能如今就用上?
如今用還早了點,由於不是全部的主流瀏覽器都支持ES6的class。若是必定要如今就用上,就須要一個工具把class
代碼轉換爲傳統的prototype
代碼,能夠試試Babel這個工具。