关于修改子类constructor父类会被影响的问题?
来源:8-1 面试总结
北乔峰27
2019-05-06
function Parent(){
this.name=‘parent’;
this.a=[1,2]
}
function Child1(){
Parent.call(this);
}
Child1.prototype=Parent.prototype;
console.log(‘Parent’,Parent.prototype.constructor);//Parent
Child1.prototype.constructor=Child1;
console.log(‘Parent’,Parent.prototype.constructor);//Child1
var s1=new Child1();
var s2=new Parent();
console.log(s1.constructor,s2.constructor);//Child1 Child1
老师,Child1.prototype=Parent.prototype之后,再设置Child1.prototype.constructor=Child1;,将子类的constructor指向子类,为什么Parent.prototype.constructor也指向了Child1啊?
是不是因为设置了Child1.prototype=Parent.prototype的缘故啊?
就好像:
var obj={a:1};//obj相当于Parent的prototype,obj.a相当于Parent.prototype.constructor
var obj2=obj;//相当于设置了Child1.prototype=Parent.prototype
obj2.a=2;//相当于修改了Child1.prototype.constructor=Child1;
console.log(obj.a);//所以父类的constructor也会随之改变
我按照这个理解对嘛老师?
1回答
-
快乐动起来呀
2019-05-15
其实很简单你把两个类的原型对象都指向一个地址,每个类的构造函数都在原型对象上,所以就只能是一个
00
相似问题
回答 2
回答 1