javascript中實現繼承的幾種方式
阿新 • • 發佈:2018-09-17
eat 共享 all cto 原型 構造 child 構造函數 java
javascript中實現繼承的幾種方式
1、借用構造函數實現繼承
function Parent1(){ this.name = "parent1" } function Child1(){ Parent1.call(this); this.type = "child1"; }
缺點:Child1無法繼承Parent1的原型對象,並沒有真正的實現繼承(部分繼承)
2、借用原型鏈實現繼承
function Parent2(){ this.name = "parent2"; this.play = [1,2,3]; } function Child2(){this.type = "child2"; } Child2.prototype = new Parent2();
缺點:原型對象的屬性是共享的
3、組合式繼承
function Parent3(){ this.name = "parent3"; this.play = [1,2,3]; } function Child3(){ Parent3.call(this); this.type = "child3"; } Child3.prototype = Object.create(Parent3.prototype); Child3.prototype.constructor= Child3
javascript中實現繼承的幾種方式