首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >火狐与Chrome在原型继承上的差异

问火狐与Chrome在原型继承上的差异
EN

Stack Overflow用户
提问于 2012-12-07 04:40:52
回答 1查看 325关注 0票数 6

以获取以下代码:

代码语言:javascript
复制
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{}。

谁能告诉我为什么它们显示不同,以及是否有人遇到过这个问题?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-12-07 06:12:51

事实(致谢@IHateLazy):

aspenProto.constructor是Mammal。这是因为constructor实际上是Mammal.prototype的一个属性,在方法创建时设置。Canine.prototype.constructor不是Canine,因为原型(持有constructor属性)已被new Mammal()覆盖。

测试:

代码语言:javascript
复制
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属性。

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13752143

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档