想问一下大家
```
function A(){
this.name="a";
this.toString=function(){
return this.name;
}
}
function B(){
this.name="b";
}
B.prototype=new A();
var b=new B();
console.log(b.name) //b
console.log(b.toString()) //b
console.log(b.constructor) //A()
console.log(b.proto==B.prototype) //true
```,这里的B的原型对象指向了A的一个实例, b.constructor指向的为什么是函数对象A啊,
因为b.proto==B.prototype为true
__proto__不是指向器构造函数的原型对象吗 那么b的构造函数应该是B啊
挺有意思的,之前都没发现。
首先你需要知道 constructor 是绑定在构造函数的 prototype 上的,然后你要知道 new 命令干了什么。
new 干了什么:创建一个空对象,并把这个空对象的 proto 指向构造函数的 prototype,然后 this 指向该对象。
new A() 所生成的对象的 proto.prototype.constructor 指向 A(),然后因为你 B.prototype=new A() 改写了 B 的 prototype,所以原本 B.prototype.constructor 属性不再存在。当你访问 b.constructor 时,在 B.prototype 自然找不到 constructor,此时就往 B.prototype.proto 上去找了,所以 console.log(b.constructor) //A()。
佥望三十 的回答很给力了。
我补充一些,楼主贴的代码,一般在继承的时候使用,需要修复构造函数。
B.prototype=new A(); // 这行后面修复
B.prototype.constructor = B; // 修复构造函数
这样 b.constructor 就是 B 了。