Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

javascript

How to use Object.create in Javascript

Ayesha Naeem

The Object.create() method uses an existing object as a prototype to create a new object.

Prototype

The Object.create() method has the following prototypes:

Prototype #1

Object.create(proto)

Prototype #2

Object.create(proto, propertiesObject)

Parameters and return value

The Object.create() function takes proto as input in both prototypes, as well as an optional input, propertiesObject, in the second prototype.

  • proto: The prototype of the newly created object. proto must be an object or null.
  • propertiesObject: The properties of the newly created object.

The Object.create() function returns a newly created object with the given prototype and properties.

Example

The following example demonstrates how to create an object using the Object.create() function in Javascript.

  • The program creates an object fruit with the properties isFruit and printFuit.
  • The program then creates another object, newFruit, using fruit as the prototype. It adds a new property, name, to newFruit and overwrites its existing property isFruit.
  • The program calls the printFruit() function, which displays information about the fruit using its properties.
// create object
const fruit = {
  isFruit: false,
  printFruit: function() {
    console.log(`Is ${this.name} a fruit? ${this.isFruit}`);
  }
};

// create a new object
const newFruit = Object.create(fruit);

// create a new property
newFruit.name = 'Mango'; 

// overwrite the isFruit property
newFruit.isFruit = true; 

newFruit.printFruit();

RELATED TAGS

javascript

CONTRIBUTOR

Ayesha Naeem
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring