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();
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.
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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With