使用原型继承为什么会改变子类的构造函数呢?看代码:var A = function (){ console.log('A');
};var B = function (){ console.log('B');
};var C = function (){ console.log('C');
};
B.prototype= new A();var b = new B();var c = new C();console.log(b.constructor.toString()); //奇怪啊console.log(c.constructor.toString());第一个console输出结果竟然是:function (){console.log('A');}不是很理解为什么会是这个结果,求大神解答
1 回答

慕婉清6462132
TA贡献1804条经验 获得超2个赞
B.prototype= new A();
是赋值操作,所以 A.prototype.contructor
就赋值给了B.prototype
在new B();
实例化的过程中其实是将B.prototype克隆出来 再让B构造函数处理后返回
因此需要重新指定
B.prototype= new A();B.prototype.contructor = B;
另外,继承我个人建议用Object.create实现
B.prototype = Object.create(A.prototype);B.prototype.contructor = B; //这样继承就不用去实例化一次A
添加回答
举报
0/150
提交
取消