1、原型链继承
function One (){
this.number = 1
this.arr = ['A']
}
Son.prototype = new One()
function Son(){
}
const son1 = new Son()
const son2 = new Son()
son1.number = 2
son1.arr.push('B')
console.log(son1.number) // 2
console.log(son2.arr) // [ 'A', 'B' ]
console.log(son2.number) // 1
console.log(son2.arr) // [ 'A', 'B' ]
缺点:复合类型数据改变会影响所有子函数
2、构造函数继承
function One (){
this.arr = ['A']
this.fn = function(){
// ...
}
}
function Son(){
One.call(this)
}
const son1 = new Son()
const son2 = new Son()
son1.arr.push('B')
console.log(son1.arr) // [ 'A', 'B' ]
console.log(son2.arr) // [ 'A' ]
console.log(son1.fn === son2.fn) // false
缺点:如果属性有公用函数,重复多了会浪费内存
3、组合继承
顾名思义,也就是以上两种方式的综合
function One(){
this.number = 1
this.arr = []
}
One.prototype.fn = function(){
// ...
}
function Two(){
One.call(this)
}
const son1 = new Two()
const son2 = new Two()
son1.number ++
son1.arr.push(1)
console.log({...son1})
console.log({...son2})
网友评论