The Object getPrototypeOf() method
By Flavio Copes
Learn how the JavaScript Object.getPrototypeOf() method returns the prototype of an object, and why it returns null for an object that has no prototype.
Object.getPrototypeOf() returns the prototype of an object. The prototype is the object JavaScript looks at when a property is not found on the object itself.
Usage:
Object.getPrototypeOf(obj)
Example:
const animal = {}
const dog = Object.create(animal)
const prot = Object.getPrototypeOf(dog)
animal === prot //true
dog was created with animal as its prototype, and getPrototypeOf() confirms it.
Why use it instead of proto?
You might have seen code reading dog.__proto__. That property is a legacy accessor, kept around for old code. Object.getPrototypeOf() is the standard way to do the same thing, and it’s what you should use.
It’s handy when you want to check what an object inherits from. Every object literal, for example, has Object.prototype as its prototype:
const flavio = { name: 'Flavio' }
Object.getPrototypeOf(flavio) === Object.prototype //true
That’s where methods like hasOwnProperty() come from. They live on Object.prototype, and flavio reaches them through the chain.
Walking the prototype chain
You can call the method repeatedly to walk up the chain. An array points to Array.prototype, which points to Object.prototype:
const list = [1, 2, 3]
Object.getPrototypeOf(list) === Array.prototype //true
Object.getPrototypeOf(Array.prototype) === Object.prototype //true
Class instances follow the same rule. The prototype of an instance is the class’s prototype object, not the class itself:
class Dog {}
const rex = new Dog()
Object.getPrototypeOf(rex) === Dog.prototype //true
Object.getPrototypeOf(rex) === Dog //false
This is what instanceof checks behind the scenes. rex instanceof Dog is true because Dog.prototype shows up somewhere in the prototype chain of rex.
There is also a companion method, Object.setPrototypeOf(), which changes the prototype of an existing object. Avoid it when you can. Changing a prototype after creation is slow, and passing the prototype to Object.create() up front is the better pattern.
When do we get null?
If the object has no prototype, we get null. This is the case of Object.prototype, the end of every chain:
Object.getPrototypeOf(Object.prototype) //null
Objects created with Object.create(null) have no prototype either:
const bare = Object.create(null)
Object.getPrototypeOf(bare) //null
Be careful with objects like bare. They don’t inherit anything, so calling bare.hasOwnProperty('name') throws an error. The method is not there, because there’s no prototype to find it on. Check for that case, or stick to regular object literals when you don’t need a prototype-free object.
Related posts about js: