CodeBlanks Logo Icon CodeBlanks

__proto__ and Object.getPrototypeOf

JavaScript course · Advanced · Lesson 14/100

Learn an object's prototype with __proto__ and Object.getPrototypeOf.

__proto__ and Object.getPrototypeOf

You can reach an object's prototype in two ways. The legacy way is the __proto__ property; it is now deprecated. The recommended way is the Object.getPrototypeOf(obj) function.

const rex = new Animal('Rex');
Object.getPrototypeOf(rex); // Animal.prototype
rex.__proto__;              // same result, but deprecated

Both return the same object. Still, Object.getPrototypeOf is safer in new code.

Writing the prototype

To read the prototype, use Object.getPrototypeOf. To write it, two safe options exist: create a new object with Object.create(proto), or change an existing one with Object.setPrototypeOf(obj, proto).

const base = { greet() { return 'hello'; } };
const child = Object.create(base);
// child now uses base as its prototype

Avoid assigning to __proto__ directly; you may see it in old code, but modern projects avoid it.

Exercise Compare the prototypes of two objects

Define the Animal constructor: assign the name parameter to this.name. Create two objects a and b with new Animal('Rex') and new Animal('Max'). Print Object.getPrototypeOf(a) === Object.getPrototypeOf(b) with console.log.

Show example solution
function Animal(name) {
  this.name = name;
}
const a = new Animal('Rex');
const b = new Animal('Max');
console.log(Object.getPrototypeOf(a) === Object.getPrototypeOf(b));

Test yourself

  1. Which is the recommended way to read an object's prototype?

    • Object.getPrototypeOf(obj)
    • obj.__proto__
    • obj.prototype
    • Object.prototype
    Show answer

    Object.getPrototypeOf(obj) — Correct! Object.getPrototypeOf is the recommended way.

  2. Read the prototype

    const proto = Object.____;
    Show answer
    const proto = Object.getPrototypeOf(rex);
  3. Match methods to their uses

    __proto__
    deprecated
    Object.getPrototypeOf
    recommended read
    Object.create
    new object + prototype
    Object.setPrototypeOf
    change existing

All lessons in Advanced