2014-04-12 9 views
6

Anbetracht MDN's Object.create polyfill:Warum legt MDNs `Object.create` Polyfill 'prototype.constructor` nicht fest?

if (typeof Object.create != 'function') { 
    (function() { 
    var F = function() {}; 
    Object.create = function (o) { 
     if (arguments.length > 1) { throw Error('Second argument not supported');} 
     if (o === null) { throw Error('Cannot set a null [[Prototype]]');} 
     if (typeof o != 'object') { throw TypeError('Argument must be an object');} 
     F.prototype = o; 
     return new F(); 
    }; 
    })(); 
} 

Fokussierung vor allem auf diesen beiden Linien:

F.prototype = o; 
return new F(); 

Ich habe mich gefragt, warum ist es nicht angebracht F.prototype.constructor = F; gesetzt?

F.prototype = o; 
F.prototype.constructor = F; // why not? 
return new F(); 
+1

Warum möchten Sie 'Konstruktor' auf' F' setzen? Es ist nur ein interner Helfer. Was wäre der Vorteil? –

+5

Eine weitere Sache ist, dass Polyfills das Verhalten so nah wie möglich nachahmen sollten und (ohne in der Lage zu sein, jetzt zu testen) das gegebene Polyfill "({}). Constructor == Object.create ({}) 'true' wie für den nativen' Object.create' –

+0

Ich denke t.nieses zweiter Kommentar (über genaue Mimikry, anstatt ideal Verhalten) ist die richtige Antwort. – Chris

Antwort

3

Ich habe mich gefragt, warum ist es nicht für angebracht F.prototype.constructor = F ;? einstellen

F ist eine temporäre Funktion, und es scheint, absichtlich, dass es keine Möglichkeit, es zu referenzieren von außen Object.create ist.

Verwandte Themen