JavaScript之各類繼承方式和優缺點javascript
function Parson(){ this.name = 'hy' } Parson.prototype.getName = function(){ console.log(this.name) } function Child(){ } Child.prototype = new Parson() var Child1 = new Parson() Child1.getName() // hy
問題:java
function Parson(){ this.name = 'hy' this.age = [13,15] } Parson.prototype.getName = function(){ console.log(this.name) } function Child(){ } Child.prototype = new Parson() var Child1 = new Child() Child1.age.push(16) console.log(Child1.age) // [ 13, 15, 16 ] var Child2 = new Child() console.log(Child2.age) // [ 13, 15, 16 ] Child1.getName() // hy Child2.getName() // hy
2. 在建立 Child 的實例時,不能向Parent傳參函數
2.借用構造函數繼承(經典繼承)this
function Parson(){ this.names = ['hy', 'ycl'] } function Child(){ Parson.call(this) } var child1 = new Child() child1.names.push('zz') console.log(child1.names) // [ 'hy', 'ycl', 'zz' ] var child2 = new Child() console.log(child2.names) // [ 'hy', 'ycl' ]
優勢:spa
function Parson(name){ this.names = name } function Child(name){ Parson.call(this , name) } var child1 = new Child('hy') console.log(child1.names) // hy var child2 = new Child('ycl') console.log(child2.names) // ycl
問題prototype