6

次のコードの場合:

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 (Firefox) は を伝えたいのですaspenProtoMammal{}、Chrome は と言っていCanine{}ます。

表示が異なる理由と、他の誰かがこの問題に遭遇したかどうか教えてもらえますか?

4

1 に答える 1

4

事実 (クレジットは @IHateLazy に送られます):

aspenProto.constructorですMammal。これは、constructor実際には Mammal.prototype の属性であり、メソッドの作成時に設定されるためです。(プロパティを保持する) プロトタイプが によって上書きされたため、Canine.prototype.constructor は ではありません。Canineconstructornew 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

結論:

constructorFirebug は常にオブジェクトの独自のプロパティに依存して名前を付けます。constructorが名前付き関数の場合、 constructor name(書き込み可能ではありません - @IHateLazy に感謝します) を使用します。constructorプロパティが無名関数であるか、関数ではない場合、Firebug は代わり"Object"に を使用します。

Chrome は、各オブジェクトの実際のコンストラクターを内部プロパティとして保持します。そのプロパティにアクセスできない (オブジェクトが構築されていない) 場合、または Object である場合にのみconstructor、オブジェクトのプロパティを調べます。コンストラクターが名前付き関数の場合、内部に格納された名前を使用します。コンストラクターが関数ではない場合、または匿名の場合は、nameプロパティを使用します。

于 2012-12-06T22:12:50.903 に答える