How to usefunctions in a Constructor function in Javascript
We can also add certain functions in a Constructor function, which can be called for any object.
Example:
Javascript
function Employee(name, id, job) { this .name = name; this .id = id; this .job = job; } /* Adding intro() method to the Prototype property of Employee */ Employee.prototype.intro = function () { console.log( 'My name is ' + this .name + ' and I am a ' + this .job); }; // Creating an Object from prototype let Employee1 = new Employee( 'Stephen' , 2364, 'developer' ); let Employee2 = new Employee( 'Maria' , 8896, 'tester' ); // Using intro method for Employee objects Employee1.intro(); Employee2.intro(); |
My name is Stephen and I am a developer My name is Maria and I am a tester
After creating two objects Employee1 and Employee2, we called Employee1.intro() and Employee2.intro() . At first, it will check if the property’s name and job are present in the respective objects. If not, then that property will be considered undefined. Thus, a constructor defines all the properties and methods that an object will inherit.
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