JS继承

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

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

function func (){}; spa

若是,用 new 运算符生成一个新的对象,prototype

newObj = new func();code

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

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

此时,若是用instanceof 测试,newObj instance of func ,为true;//newObj.__proto__ = func.prototype 继承

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

而若是为了继承,替代了function自带的prototype的话,由于整个prototype被替换了,那么上面的constructor属性固然也一块儿被替代了。function

而若是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]
相关文章
相关标签/搜索