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 @   Esther_Cheung  阅读(131)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
点击右上角即可分享
微信分享提示