JavaScript中常見的幾種繼承方式
原型繼承
function Parent(name) { this.name = name } Parent.prototype.getName = function(){ return 'parentPrototype' + ' ' + this.name; } function Son() { } Son.prototype = new Parent(); console.log(new Son())
內存圖
分析
原型繼承的原理就是把子類的prototype指向父類的實例身上,這樣做,子類就可以使用父類的屬性和方法了,但是,無法初始化父類的屬性,這個時候,盜用構造函數繼承就出現了
盜用構造函數繼承
function Parent(name) { this.name = name } Parent.prototype.getName = function(){ return 'parentPrototype' + ' ' + this.name; } function Son(name) { Parent.call(this, name) } console.log(new Son('jack'))
分析
盜用構造函數的原理簡單理解就是吧父類函數的代碼 copy
到子類里面,在上述代碼中相當于把父類的this.name = name
在子類里執(zhí)行了一次,這樣的話,就可以在子類實例化的時候初始化父類的一些屬性
如果這樣的話就取不到父類原型身上的方法了,為了解決這個問題,組合繼承就出現了
組合繼承
function Parent(name) { this.name = name } Parent.prototype.getName = function(){ return 'parentPrototype' + ' ' + this.name; } function Son(name) { Parent.call(this, name) // 第二次調用 } Son.prototype = new Parent() // 第一次調用 console.log(new Son('jack'))
組合繼承,也稱為偽經典繼承,結合了原型繼承和盜用構造函數繼承,既可以初始化父類的方法,又可以取到父類的原型身上的方法
可以看到這種繼承方式name會被多次創(chuàng)建,雖然在使用上沒什么區(qū)別,但是會多開辟一些無用內存,而且還會多調用一次函數
原型鏈繼承
const parent = { name: 'jack', getName() { return this.name } } const son = Object.create(parent) console.log(son)
這種繼承適用于想在一個對象的基礎上添加一個新的對象,這個新的對象可以有自己獨立的屬性
還可以有自己的屬性:
const parent = { name: 'jack', getName() { return this.name } } const son = Object.create(parent, { age: { value: 18, enumerable: true, writable: true, configurable: true } }) console.log(son)
寄生式繼承
const parent = { name: 'jack', getName() { return this.name } } function createObj(origin){ const res = Object(origin); res.age = 18; res.getAge = function() { return this.age }; return res } const son = createObj(parent) console.log(son)
寄生式繼承就是類似于工廠模式,經過它創(chuàng)建的函數,會有一些自帶的值
寄生組合式繼承
function Parent(name) { this.name = name; } Parent.prototype.getName = function () { return this.name; } function Son(name) { Parent.call(this, name) }; function inhertPrototype(Son, Parent) { const res = Object(Parent.prototype); // 創(chuàng)建目標對象的原型對象 // 可以理解為復制父類對象prototype的屬性,這樣做可以少調用一次父類的實例化操作 res.constructor = Son // 將構造函數指向son Son.prototype = res //將子類的prototype 指向父類創(chuàng)建的原型對象,這樣子類既可以使用父類的方法,又不用實例化父類 } inhertPrototype(Son, Parent) console.log(new Son('jack'))
寄生組合式繼承 被稱為最佳繼承模式 他解決了組合繼承父類函數被調用兩次的問題,同時又不會給子類的prototype
加上父類的無用的屬性
可以對比組合繼承的圖看一下,prototype
上少了 name
,最佳的繼承方式
到此這篇關于JavaScript中常見的幾種繼承方式的文章就介紹到這了,更多相關js繼承方式內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
關于document.cookie的使用javascript
構造通用的cookie處理函數 cookie的處理過程比較復雜,并具有一定的相似性。因此可以定義幾個函數來完成cookie的通用操作,從而實現代碼的復用。2010-10-10