// 1,借助call
console.log('1111111111111111111111111111111111111111111111')
function Father1 (){
this.name= '我是Father1'
this.fun = function (){
console.log('我是Father1属性方法fun')
}
function funct() {
console.log('我是Father1方法funct')
}
}
function Child1 (){
Father1.call(this)
this.sonName = '我是Child1'
}
let demo1 = new Child1()
console.log(demo1.name,demo1.sonName)
demo1.fun()
//demo1.funct()
console.log('call弊端,demo1.funct() 识别不到父类的方法')
// 2,借助原型链实现(prototype)
console.log('222222222222222222222222222222222222222')
function Father2(){
this.name = '我是Father2'
this.arr = [1,2,3]
}
function Child2(){
this.sonName = '我是Child2'
}
Child2.prototype = new Father2()
let child2_1 = new Child2()
let child2_2 = new Child2()
console.log(child2_1.name)
child2_1.arr.push(4)
console.log(child2_1.arr,child2_2.arr)
console.log('prototype弊端,共用一个原型,修改值时互相影响')
// 3,将前两种合并
console.log('33333333333333333333333333333333333333')
function Father3(){
this.name = '我是Father3'
this.arr = [1,2,3]
}
function Child3(){
Father3.call(this)
this.sonName = '我是Child3'
}
Child3.prototype = new Father3()
let child3_1 = new Child3()
let child3_2 = new Child3()
console.log(child3_1.name)
child3_1.arr.push(4)
console.log(child3_1.arr,child3_2.arr)
console.log('弊端,Child3.prototype = new Father3()执行了两次')
console.log('44444444444444444444444444444444444444')
function Parent4 () {
this.name = 'parent4';
this.play = [1, 2, 3];
}
function Child4() {
Parent4.call(this);
this.type = 'child4';
}
Child4.prototype = Parent4.prototype;
let s3 = new Child4();
let s4 = new Child4();
console.log(s3.constructor)
console.log(s4.constructor)
console.log('弊端:s3,s4的构造函数是Parent4,显然是有问题的')
console.log('55555555555555555555555555555555555555')
function Parent5 () {
this.name = 'parent5';
this.play = [1, 2, 3];
}
function Child5() {
Parent5.call(this);
this.type = 'child5';
}
Child5.prototype = Object.create(Parent5.prototype);
Child5.prototype.constructor = Child5;
let child5_1 = new Child5()
let child5_2 = new Child5()
console.log(child5_1.name)
console.log(child5_2.name)
console.log('现阶段继承的最佳实践')
console