繼承實現的幾種方式es6
1.藉助call實現繼承數組
function p1() { this.name = 'p1' this.say = function () { console.log(this.name) } } var Parent1 = p1 Parent1.prototype.show = function show() { console.log(this.name) } function Child1() { Parent1.call(this) this.type = 'c1' } console.log(new Child1()) // Child1 { name: 'p1', say: [Function], type: 'c1' } /* * p1 {name: "p1", say: ƒ} name: "p1" say: ƒ () __proto__: show: ƒ show() constructor: ƒ p1() __proto__: Object * */ console.log(new Parent1())
這種方式ide
function Parent2() { this.name = 'p2' this.play = [1,2,3] this.say = function() { console.log(this.name) } this.obj = { habbit: '學習' } } function Child2 () { this.type = 'c2' } Child2.prototype = new Parent2() console.log(new Child2()) var s1 = new Child2(); var s2 = new Child2(); s1.play.push(4); console.log(s1.play, s2.play); // (4) [1, 2, 3, 4] (4) [1, 2, 3, 4]
這種方式函數
function Parent3() { this.name = 'p3' this.play = [1,2,3,4] this.say = function(){ console.log(this.play) } this.obj = { news: 'sdsds' } } function Child3() { Parent3.call(this) this.type = 'c3' } Child3.prototype = new Parent3() var s3 = new Child3() var s4 = new Child3() s3.play.push(9) s3.obj.news = 'nff' s3.say= function() {console.log(2222)} console.log(s3.play, s4.play) console.log(s3.obj.news, s4.obj.news) s3.say() s4.say()
這種方式學習
會多執行Child3.prototype = new Parent3() 這一句優化
function Parent4() { this.name = 'p4' this.play = [1,2,3,4] this.say = function(){ console.log(this.play) } this.obj = { news: 'sdsds' } } function Child4() { Parent4.call(this) this.type = 'c4' } Child4.prototype = Parent4.prototype var s3 = new Child4(); var s4 = new Child4(); console.log(s3)
function Parent5() { this.name = 'p5' this.play = [1,2,3,4] this.say = function(){ console.log(this.play) } this.obj = { news: 'sdsds' } } function Child5() { Parent5.call(this) this.type = 'c5' } Child5.prototype = Object.create(Parent5.prototype) Child5.prototype.constructor = Child5
這種方式,較經常使用,固然,es6推除了class,直接繼承,就不用這麼麻煩了this