Javascript Object.create()

The JavaScript Object.create() method creates a new object using prototype of given object.

The syntax of the create() method is:

Object.create(proto, propertiesObject)

The create() method, being a static method, is called using the Object class name.


create() Parameters

The create() method takes in:

  • proto - The object which should be the prototype of the newly-created object.
  • propertiesObject (optional) - An object whose enumerable own properties specify property descriptors to be added to the newly-created object. These properties correspond to the second argument of Object.defineProperties().

Return value from create()

  • Returns a new object with the specified prototype object and properties.

Note: If proto is not null or an Object, TypeError is thrown.


Example: Using Object.create()

let Animal = {
  isHuman: false,
  sound: "Unspecified",
  makeSound() {
    console.log(this.sound);
  },
};

// create object from Animal prototype
let snake = Object.create(Animal);
snake.makeSound(); // Unspecified

// properties can be created  and overridden
snake.sound = "Hiss";
snake.makeSound(); // Hiss

// can also directly initialize object properties with second argument
let properties = {
  isHuman: {
    value: true,
  },
  name: {
    value: "Jack",
    enumerable: true,
    writable: true,
  },
  introduce: {
    value: function () {
      console.log(`Hey! I am ${this.name}.`);
    },
  },
};

human = Object.create(Animal, properties);
human.introduce(); // Hey! I am Jack.

Output

Unspecified
Hiss
Hey! I am Jack.

Recommended Reading: Javascript Object isPrototypeOf()

Did you find this article helpful?