I am able to access Object.getPrototypeOf
method, but why is the same not available for instantiated objects?
const obj = {}
obj.getPrototypeOf // is not a function
I am able to access Object.getPrototypeOf
method, but why is the same not available for instantiated objects?
const obj = {}
obj.getPrototypeOf // is not a function
3
Answers
Because it’s a static method (it’s meant to be used on a class, not an instance)
Example:
It’s a static method, you can’t use it on an instance.
Try instead:
The main reason, as others have noted, is that it’s a static method on the
Object
constructor, not an instance or prototype function. So the correct way to use it isconst proto = Object.getPrototypeOf(theObject);
. But read on for why you might not have wanted to use an object method for this even if it did have one.Objects do have a
__proto__
accessor property but using it is a Bad Idea™ because A) The object may not have it,¹ and B) Even if the object does have it, it may lie to you, just as it can with the prototype methodhasOwnProperty
that checks to see if the object has an "own" property with a given name. That opportunity for the object to lie is one motivation for moving away from putting these things on the prototype (along with avoiding web compatibility problems and improving JavaScript engine performance). Recently, a new static method onObject
,Object.hasOwn
, was added to replace the prototype functionhasOwnProperty
specifically because of this issue. LikegetPrototypeOf
, it’s a static method onObject
, not a prototype method, and it won’t lie to you. (Proxy objects notwithstanding.)So in those rare situations you need to get the prototype of an object, just do it via
Object.getPrototypeOf(theObject)
.Example of objects with no
__proto__
accessor property: