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]
相關文章
相關標籤/搜索