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

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.



Reffered: https://www.geeksforgeeks.org


JavaScript

Related
What is Event Bubbling ? What is Event Bubbling ?
JavaScript TypedArray.prototype.toReversed() Method JavaScript TypedArray.prototype.toReversed() Method
What does !== undefined mean in JavaScript ? What does !== undefined mean in JavaScript ?
How to Convert an Object into Array of Objects in JavaScript ? How to Convert an Object into Array of Objects in JavaScript ?
How to Parse Float with Two Decimal Places in TypeScript ? How to Parse Float with Two Decimal Places in TypeScript ?

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
14