Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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();
like image 492
ChaseMoskal Avatar asked Apr 12 '14 19:04

ChaseMoskal


People also ask

What is the use of prototype constructor in JavaScript?

constructor. The constructor property returns a reference to the Object constructor function that created the instance object. Note that the value of this property is a reference to the function itself, not a string containing the function's name.

How do you set a prototype of an object?

The Object. setPrototypeOf() method sets the prototype (i.e., the internal [[Prototype]] property) of a specified object to another object or null. All JavaScript objects inherit properties and methods from a prototype. It is generally considered the proper way to set the prototype of an object.

What is the difference between constructor and prototype in JavaScript?

A constructor is a pointer. It points to the Function() that created the point from which you are retrieving the constructor from. The keyword prototype is a property of Function() objects. No other type of objects have this property.


1 Answers

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.

like image 87
erikvold Avatar answered Oct 31 '22 21:10

erikvold