CodeBlanks Logo Icon CodeBlanks

Object.create

JavaScript course · Advanced · Lesson 15/100

Learn to create objects using an existing prototype with Object.create.

Object.create

Object.create(proto) creates a new object whose prototype is the object you pass in. The new object can access every property on proto.

const animalProto = {
  describe() { return 'I am an animal'; }
};
const rex = Object.create(animalProto);
rex.describe(); // 'I am an animal'

rex has no describe property of its own; it comes through the prototype chain. This is the basic way to set up prototype-based objects without new.

Own properties via the second argument

The second argument of Object.create defines the new object's own properties. Each property is written as a descriptor object.

const rex = Object.create(animalProto, {
  name: { value: 'Rex', enumerable: true }
});

Here rex both reuses the describe method from animalProto and has its own name property. The second argument is optional and often left out.

Exercise Build animalProto and rex with Object.create

Define an object animalProto with a describe method that returns 'I am an animal'. Create rex with Object.create(animalProto). Call console.log(rex.describe()) to invoke the inherited method.

Show example solution
const animalProto = {
  describe() {
    return 'I am an animal';
  }
};
const rex = Object.create(animalProto);
console.log(rex.describe());

Test yourself

  1. What does Object.create(null) produce?

    • An object whose prototype is Object.prototype
    • An empty array
    • An object with no prototype
    • A variable holding null
    Show answer

    An object with no prototype — Correct! Object.create(null) gives a prototype-less object.

  2. Complete the Object.create call

    const rex = Object.____;
    Show answer
    const rex = Object.create(animalProto);
  3. Match creation patterns to their results

    Object.create(proto)
    new object + prototype
    new Constructor()
    constructor + prototype
    {}
    Object.prototype
    Object.create(null)
    no prototype

All lessons in Advanced