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); |
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