JavaScript Reference ยท Object
Object.getPrototypeOf()
Reference for JavaScript Object.getPrototypeOf(): read an object's prototype, walk the prototype chain and compare it with instanceof and the __proto__ property.
Object.getPrototypeOf() returns the prototype of an object: the object it inherits from, which is the next link in its prototype chain. The result is null when the chain ends.
It is the standard, reliable way to read a prototype. It works even for objects that have no __proto__ property, such as those created with Object.create(null).
Object.getPrototypeOf([]) === Array.prototype; // true
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
Object.getPrototypeOf(obj)
| Name | Description |
|---|---|
obj |
The value whose prototype you want. Primitives are converted to their wrapper objects. |
Return value: the prototype object, or null if there is none.
Exceptions: a TypeError if obj is null or undefined.
Usage notes
- Prefer it to
__proto__. The__proto__accessor is a legacy feature that exists only on objects inheriting fromObject.prototype.Object.getPrototypeOf()works for everything. - Not the same as
.prototype. Functions and classes have aprototypeproperty, which is the object given to their instances.Object.getPrototypeOf(fn)is the prototype of the function itself. For an instance,Object.getPrototypeOf(rex) === Dog.prototype. - Class inheritance links constructors too. The prototype of a subclass is its parent class.
- Primitives work: the prototype of
"text"isString.prototype. - The chain ends at
null.Object.prototypehas no prototype. Loops that walk the chain should stop onnull. - Comparisons:
instanceofwalks the same chain and checks it for you, andObject.prototype.isPrototypeOf()checks whether one object appears in another's chain. - Changing it is possible with
Object.setPrototypeOf(), but it is slow and best avoided after creation. Pick the prototype when creating the object, withObject.create()orclass.
Browser support
Object.getPrototypeOf() is available in every browser and JavaScript runtime.
Related
Object.setPrototypeOf(),Object.create(),instanceof- Concept: prototypes and the prototype chain
- Lessons: Prototypes, Inheritance