标签:src type 属性 优化 组合继承 fun const 类的属性 原型对象
继承实现的几种方式
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())
这种方式
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,直接继承,就不用这么麻烦了
标签:src type 属性 优化 组合继承 fun const 类的属性 原型对象
原文地址:https://www.cnblogs.com/ichthyo-plu/p/11826641.html