Why doesn't MDN's `Object.create` polyfill set `prototype.constructor`?
Asked Answered
P

1

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();
Piquet answered 12/4, 2014 at 19:31 Comment(3)
Why do you want to set constructor to F? It is just an internal helper. What would be the advantage?Ultan
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.createUltan
I think t.niese's second comment (about accurate mimicry, rather than ideal behavior) is the right answer.Pontefract
W
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.

Wilber answered 17/6, 2015 at 20:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.