JS继承

JS中的继承主要依靠prototype实现。

当一个function被创建,它默认会有一个prototype对象。

function func (){}; 

如果,用 new 运算符生成一个新的对象,

newObj = new func();

那么 ,prototype的constructor属性指向func(此时作为class)

而此时,newObj的__proto__属性指向的是这个prototype对象,可以使用这个对象上的数据和方法。

此时,如果用instanceof 测试,newObj instance of func ,为true;//newObj.__proto__ = func.prototype 

而prototype 自身的__proto__属性指向它的prototype。

而如果为了继承,替代了function自带的prototype的话,因为整个prototype被替换了,那么上面的constructor属性当然也一起被替代了。

而如果set prototype 或者 func 上面的数据,如果生成了其他实例,公用数据也会改变。解决方案:

 1 function parent1() {
 2     this.parentName = 'lily';
 3     this.parentcount = [1,2]
 4 };
 5 
 6 function children1() {
 7 
 8     this.name = 'lucy';
 9     this.age = 13;
10     parent1.call(this);//私有化数据
11 }
12 function create1(p) {
13 function f(){};
14 f.prototype = new p();
15 var  F = new f();
16 return F;
17 }
18 children1.prototype =create1(parent1);
19 children1.prototype.constructor = children1;
20 var child1 = new children1();
21 
22 
23 
24 child1.parentcount.push(2);
25 
26 var child2 = new children1();
27 child1.__proto__.constructor //children1
28 child2.parentcount //[1,2]
29 child1.parentcount //[1, 2, 2]

 

posted @ 2018-09-01 14:30  Esther_Cheung  阅读(135)  评论(0)    收藏  举报