Javascript Object Create: The Complete Guide

0
102
Object Create Method in Javascript

The Object.create() method in JavaScript creates a new object with the specified prototype object and properties.

Javascript Object Create

Javascript Object.create() is a built-in method that creates a 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

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

The Object.create() function 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, we first created a prototype object and then assigned the property to that Object. Next, 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

The Object.create() method creates 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 implement inheritance.

That’s it for this tutorial.

Related posts

Object.freeze

Object.keys

Object.assign

Object.values

Leave A Reply

Please enter your comment!
Please enter your name here

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