javascript - Null prototype, Object.prototype and Object.create -
why setting prototype property of constructor function null not prevent objects created function calling through methods on object.prototype, in same way setting prototype object.create(null) does?
that is, why case:
function foo(){} foo.prototype = null; console.log(new foo().tostring); //outputs function tostring() { [native code] } (or whatever) function foo(){} foo.prototype = object.create(null); console.log(new foo().tostring); //output undefined
in short
yes, observation correct - function constructed new operator always have object prototype in case object.prototype , indeed unlike function created object.create.
on why
one can see behavior specified in es5 language specification on javascript based on. let's see this.
in new:
quoting specification of [[construct]] method of functions indicates how object creation using new operator performed can see following specified:
if type(proto) not object, set [[prototype]] internal property of obj standard built-in object prototype object described in 15.2.4.
in object.create:
on other hand, if check out the spec object.create can see object.create(o) specifies:
set [[prototype]] internal property of obj o.
which means can set it, explicitly checks null or object in algorithm (please do follow link spec , read :))
so prototype of objects called new foo object.prototype , not null. impossible create objects no prototype without object.create using standard methods only.
Comments
Post a Comment