以获取以下代码:
function Mammal(){
this.hair = true;
this.backbone = true;
return this;
}
function Canine(){
this.sound= 'woof';
return this;
}
Canine.prototype = new Mammal();
function Dog(name){
this.tail=true;
this.name=name;
return this;
}
Dog.prototype = new Canine();
var aspen = new Dog('Aspen');
var aspenProto = aspen.__proto__Firebug (火狐)想告诉我aspenProto是Mammal{},而Chrome是Canine{}。
谁能告诉我为什么它们显示不同,以及是否有人遇到过这个问题?
发布于 2012-12-07 06:12:51
事实(致谢@IHateLazy):
aspenProto.constructor是Mammal。这是因为constructor实际上是Mammal.prototype的一个属性,在方法创建时设置。Canine.prototype.constructor不是Canine,因为原型(持有constructor属性)已被new Mammal()覆盖。
测试:
aspen.constructor = function Hello(){}; // aspen is Hello in Firebug,
// Dog in Chrome
aspen.constructor.name = "test" // still Hello in Firebug,
// name is also Hello in both
aspen.constructor = function(){}; // aspen is Object in Firebug
aspen.constructor.name = "test" // still Object in Firebug
aspen.constructor = null; // still Object and Dog
({constructor: function Hello(){}}) // Hello in Firebug AND Chrome
({constructor: function (){}}) // Object in both (not surprisingly)
({constructor:{name:"Hi"}}) // "Object" in FB, "Hi" in Chrome
x={constructor:function(){})
x.constructor.name="Hello" // x is Object in both
x=new Object()
x.constructor=function Hello(){} // x is Hello in both
new (function(){})() // Object in both
new (function(){
this.constructor=function Hello(){}
})() // Hello in both结论:
Firebug总是依赖于对象自己的constructor属性来命名它。如果constructor是一个命名函数,它将使用constructor name (它是不可写的-谢谢@IHateLazy)。如果constructor属性是一个匿名函数或者根本不是一个函数,那么Firebug将改用"Object"。
Chrome将每个对象的实际构造函数作为内部属性。只有当该属性不可访问(该对象未构造)或者是对象时,它才会查看该对象的constructor属性。如果构造函数是命名函数,则使用其内部存储的名称。如果构造函数不是函数或者是匿名的,则使用name属性。
https://stackoverflow.com/questions/13752143
复制相似问题