AppDividend
Latest Code Tutorials

Javascript Object Create: How to Create Object in JS

0

The object.create() method in JavaScript is used to create a new object with the specified prototype object and properties.

Javascript Object Create()

Javascript Object.create() is an inbuilt method that creates the new object, using an existing object as a prototype of the newly created object. It will return a new object with the specified prototype object and properties.

Syntax

The syntax of the Javascript object create() method is the following.

Object.create(prototype_object, propertiesObject)

Parameters

The Object.create method accepts two arguments.

  1. prototypeObject: Newly created objects prototype object. It has to be an object or null.
  2. propertiesObject: Properties of the new object. This argument is optional.

Return Value

It will return a new object with the specified prototype object and properties.

Let us take a simple example.

let infinityGauntlet = Object.create({});

infinityGauntlet.stoneName = 'TimeStone';

console.log(infinityGauntlet);

Output

Javascript Object Create Example | Object.create() Tutorial

In the above example, first, we have created a prototype object and then assign the property to that object. Let us take another example with the method as a property.

// app.js

const person = {
  isHuman: false,
  intro: function () {
    console.log(`My name is ${this.name} and I am intergalactic Sociopath!!`);
  }
};
const celestialCepians = Object.create(person);
celestialCepians.name = 'Thanos';
celestialCepians.isHuman = false;
celestialCepians.intro();

Output

Javascript Object Create Example

Custom and Null objects

A new object created from a completely custom object (especially one created from the null object, which is a custom object with NO members can behave in unexpected ways.

Let us take an example of a null property object.

// app.js

freshObj = Object.create({});
nullObj = Object.create(null);

console.log(typeof(nullObj));
console.log(nullObj);

Output

Object.create() Tutorial

So, the Object.create() method is used to create the new object with a specified prototype object and properties. Object.create() method returns the new object with the specified prototype object and properties.

The primary purpose of using the Object.create() method is used for implementing inheritance.

Finally, Javascript Object create() Example is over.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.