Approach 3 Using Constructor
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.
Syntax:
function Object(property1, property2) {
this.property1 = property1;
this.property2 = property2;
}
let obj = new Object(property1, property2);
Example:
Javascript
/* constructor function that will define prototype of an Employee object */ function Employee(name, id, job) { this .name = name; this .id = id; this .job = job; } // This will show Employee's prototype console.log(Employee.prototype); |
{}
{constructor: ƒ}
constructor: ƒ Employee(name, id, job)
[[Prototype]]: Object
Here, a constructor of an Employee object is defined that contains basic details of an Employee i.e. name, id, and job.
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