Approach 2 Using Prototypes

Every JavaScript function has a prototype object property that is empty by default. We can initialize methods and properties to this prototype for creating an object.

Syntax:

let obj = Object.create(Object_prototype)

Example:

Javascript




let Employee = {
    id: 565,
    department: "Finance"
}
 
let Employee1 = Object.create(Employee);
 
console.log("id :", Employee1.id);
console.log("department :", Employee1.department);


Output

id : 565
department : Finance

How to create an object with prototype in JavaScript ?

In this article, we will discuss object creation & prototypes, along with understanding the different ways for object creation & their implementation through the examples. Prototypes are the mechanism by which objects in JavaScript inherit features from another object. A prototype property is also an object whose methods and properties will be inherited by any new object.

A simple object in JavaScript can be compared with real-life objects with some properties. For instance, an Employee can be considered as an object, having the properties like “name”, “age”, “department”, “id”, etc, which is unique for each employee. 

Here are some common approaches to creating an object with a prototype in javascript.

  • Using Object Literal
  • Using Prototypes
  • Using Constructor
  • Using function constructor
  • using functions in a Constructor function

Similar Reads

Approach 1: Using Object Literal

The first method to create an object is by using Object Literal. It describes the methods and properties that the object will inherit directly....

Approach 2: Using Prototypes:

...

Approach 3: Using Constructor:

Every JavaScript function has a prototype object property that is empty by default. We can initialize methods and properties to this prototype for creating an object....

Approach 4: Using function constructor

...

Approach 5: Using functions in a Constructor function

This is a function that is used to define an object and its properties. this keyword is used to assign a value to these properties of the object....