Open In App

What is the use of the Object.create() method in JavaScript ?

Last Updated : 12 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

The Object.create() method in JavaScript is used to create a new object with a specified prototype object and optional properties. It provides a way to create objects that inherit properties and methods from a parent object, without the need for constructor functions or classes.

Syntax:

Object.create(prototype[, propertiesObject])

Parameters:

  • proto: The object which should be the prototype of the newly created object.
  • propertiesObject (optional): An object whose enumerable own properties define properties to be added to the newly created object.

Example: Here, we first define a prototype object personProto with a greet() method. Then, we create a new object john using Object.create(personProto). This makes personProto the prototype of john, allowing john to inherit the greet() method. Finally, we add a name property to john and call the greet() method, which prints “Hello, my name is John.” to the console.

Javascript




const personProto = {
  greet: function() {
    console.log(`Hello, my name is ${this.name}.`);
  }
};
 
const Geek = Object.create(personProto);
Geek.name = "Geek";
Geek.greet();


Output

Hello, my name is Geek.

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads