js中常見的6種繼承方式總結
前言
js是門靈活的語言,實現一種功能往往有多種做法,ECMAScript沒有明確的繼承機制,而是通過模仿實現的,根據js語言的本身的特性,js實現繼承有以下通用的幾種方式
溫馨提示:本文中Super函數都是指父類,Sub函數都是代表子類。同時文中會涉及到“構造函數模式”和“工廠模式”,如果不熟悉的小伙伴,可以先看看這篇介紹 js常見的4種創(chuàng)建對象方式。
1、原型繼承
實現:
function Super(){ this.a=1 }
Super.prototype.say = function(){ console.log(‘hhh') }
function Sub(){}
Sub.prototype = new Super()
const test = new Sub()
console.log( test.say() )// hhh優(yōu)點:通過原型繼承多個引用類型的屬性和方法
缺點:Sub原型變成了Super的實例,如果Super的實例某個屬性是引用值,該引用值就會被應用到所有Sub創(chuàng)建的實例中去,會有污染問題。如下
function Super(){ this.a=[1,2] }
function Sub(){}
Sub.prototype = new Super()
const test1 = new Sub()
test1.a.push(3)
console.log(test1.a)// [1,2,3]
const test2 = new Sub()
console.log(test2.a)// [1,2,3]2、盜用構造函數
實現:構造函數模式+call
function Super = function(){ this.a = 1 }
function Sub = function(){
Super.call(this)
this.b = 2
}
const test = new Sub()優(yōu)點:每個實例都會有自己的a屬性,哪怕是引用值也不會被污染
缺點:Super構造函數中的方法在每個實例上都要創(chuàng)建一遍(除非該方法聲明提到全局);Sub的實例無法訪問Super原型上的方法
3、組合繼承
實現:原型繼承+盜用構造函數繼承
function Super(){ this.a=[1,2] }
Super.prototype.say = function(){ console.log(‘hhh') }
function Sub(){
Super.call(this)
this b=2
}
Sub.prototype = new Super()
const test1 = new Sub()
console.log( test1.say() )// hhh
test1.a.push(3)
console.log(test1.a)// [1,2,3]
const test2 = new Sub()
console.log(test2.a)// [1,2]優(yōu)點:集合了【原型繼承】和【盜用構造函數繼承】的優(yōu)點
缺點:存在效率問題,Super始終會被調用兩次
4、原型式繼承
實現:
es5之前
const obj = { a:1 }
function createObj(o){
const Fn(){}
Fn.prototype = o
return new Fn()
}
const test = createObj(obj)es5之后
const obj = { a:1 }
const test = Object.create(obj)優(yōu)點:對一個對象進行淺克隆創(chuàng)建另一個對象,同時繼承該對象的原型屬性
缺點:由于是淺克隆,所以實例共享的對象屬性如果是引用值,會受污染。如下
const obj = { a:[1,2], b:2 }
const test1 = Object.create(obj)
const test2 = Object.create(obj)
test1.a.push(3)
test1.b=3
console.log(test1.a, test2.a)// [1,2,3] [1,2,3]
console.log(test1.b, test2.b)// 3 25、寄生式繼承
實現:構造函數模式+工廠模式
function createObj(o){
let clone = objectCopy(o)
clone.say=function(){
console.log(‘hhh')
}
return clone
}
const obj = { a:1 }
const test = createObj(obj)優(yōu)點:根據一個對象克隆創(chuàng)建另一個對象,并增強對象
缺點:同【盜用構造函數繼承】方法在每個實例上都要創(chuàng)建一遍
注意:objectCopy是對入參對象的復制
6、寄生式組合繼承
實現:盜用構造函數繼承 + 原型式繼承
function Super(){ this.a=[1,2] }
Super.prototype.say = function(){ console.log(‘hhh') }
function Sub(){
Super.call(this)
this b=2
}
Sub.prototype = Object.create(Super.prototype)
Sub.prototype.constructor = Sub
const test = new Sub()優(yōu)點:集合了【原型式繼承】和【盜用構造函數繼承】的優(yōu)點,效率比【組合繼承】更高。
總結
到此這篇關于js中常見的6種繼承方式的文章就介紹到這了,更多相關js的6種繼承方式內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

