继承

js继承

1
2
3
4
5
6
7
8
9
10
11
12
13
14
/**
* 借助构造函数实现继承
*/
function Parent1(){
this.name = 'parent';
}
//Parent1.prototype.say = function(){};
//给父类原型添加一个say方法,但此方法子类通过call/apply不能继承
function Child1(){
Parent1.call(this);//apply也可以实现继承
//这里实现继承的原理就是通过call/apply使父级方法的this指向子类
this.type = 'child';
}
//console.log(new Child1,new Parent1());
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/**
* 借助原型链实现继承
*/
function Parent2(){
this.name = 'parent2';
this.play = [1,2,3];
}
function Child2(){
this.type = 'child2';
}
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);

//两个的原型prototype一样,constructor一样,所以原型上的方法也是一样,S1/S2里的play增加一个数,相当于修改原型上的方法,所有继承这个 方法的实例全都会改变
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/**
* 组合方式
*/
function Parent3(){
this.name = 'parent';
this.play = [1,2,3];
}
function Child3(){
Parent3.call(this);
this.type = 'child3';
}
Child3.prototype = new Parent3();
var s3 = new Child3();
var s4 = new Child3();
s3.play.push(4);
console.log(s3.play,s4.play);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/**
* 组合继承的优化1
*/
function Parent4(){
this.name = 'parent4';
this.play = [1,2,3];
}
function Child4(){
Parent4.call(this);
this.type = 'child4';
}
Child4.prototype = Parent4.prototype;
var s5 = new Child4();
var s6 = new Child4();
s5.play.push(4);
console.log(s5,s6);
//只优化了prototype 而constructor还是一样的
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/**
* 组合继承优化2
*/
function Parent5(){
this.name = 'parent5';
this.play = [1,2,3];
}
function Child5(){
Parent4.call(this);
this.type = 'child5';
}
Child5.prototype = Object.create(Parent5.prototype);
Child5.prototype.constructor = Child5;

var s7 = new Child5();
var s8 = new Child5();

console.log(s7 instanceof Child5,s7 instanceof Parent5);
console.log(s7.constructor);
//通过Object连接修改原型,prototype不会同时改变,而construcor通过重新赋值也不会跟父类相同。