6

Considering MDN's Object.create polyfill:

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();
    };
  })();
}

Focusing particularly on these two lines:

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

I was wondering, why isn't it appropriate to set F.prototype.constructor = F;?

F.prototype = o;
F.prototype.constructor = F;  // why not?
return new F();
erikvold
  • 15,988
  • 11
  • 54
  • 98
ChaseMoskal
  • 7,151
  • 5
  • 37
  • 50
  • 1
    Why do you want to set `constructor` to `F`? It is just an internal helper. What would be the advantage? – t.niese Apr 12 '14 at 19:43
  • 5
    An additional thing is that polyfills should mimic the behavior as close as possible and (without being able to test right now) the given polyfill should evaluate `({}).constructor == Object.create({}).constructor` to `true` as it does for the native `Object.create` – t.niese Apr 12 '14 at 19:58
  • I think t.niese's second comment (about accurate mimicry, rather than ideal behavior) is the right answer. – Chris Aug 15 '14 at 00:42

1 Answers1

3

I was wondering, why isn't it appropriate to set F.prototype.constructor = F;?

F is a temporary function, and it seems intentional that there is no way to reference it from outside Object.create.

erikvold
  • 15,988
  • 11
  • 54
  • 98