標籤:class this super color const cti 函數實現 func 實現繼承
javascript實現繼承大致有如下5種方式:
第1種,通過建構函式實現繼承
function Parent() { this.name = ‘parent‘ } function Child() { Parent.call(this) this.type = ‘child‘ }
第2種,通過原型鏈實現繼承
function Parent() { this.name = ‘parent‘ } function Child() { this.type = ‘child‘ } Child.prototype = new Parent() Child.prototype.constructor = Child
第3種,組合第1種和第2種方式
function Parent() { this.name = ‘parent‘ } function Child() { Parent.call(this) this.type = ‘child‘ } Child.prototype = new Parent() Child.prototype.constructor = Child
第4種,是對第3種的最佳化,也是推薦的方式
function Parent() { this.name = ‘parent‘ } function Child() { Parent.call(this) this.type = ‘child‘ } Child.prototype = Object.create(Parent.prototype) Child.prototype.constructor = Child
第5種,使用es6文法
class Parent { constructor() { this.name = ‘parent‘ } } class Child extends Parent { constructor() { super() this.type = ‘child‘ } }
談談javascript繼承