javascript-prototype

JavaScript Object Prototypes

Javascript object prototype attribute is used to define properties and methods that can be accessed by all the instances of the object.

In javascript, every function and object has a by default property known as the prototype. Let us understand it with the help of an example.

Source Code

Try it yourself

Code Explanation

In this example, we are trying to access the prototype of a Person constructor function. Here, prototype of Person constructor function is empty object { }.Since we do not assign any value to the prototype.

Prototype Inheritance

Javascript prototype is basically used to add properties and methods to the constructor function so that objects can inherit properties and methods from the prototype.

Adding Properties To The Constructor Function using Prototype

Following is the general syntax to add the property to an object constructor function:

General Syntax

Try it yourself

Source Code

Try it yourself

Code Explanation

In the above example, it is clear that person1 & person 2 inherit the property education from the prototype of the person construction function.

Adding Methods to a Constructor Function Using Prototype

Javascript object method can be added to a constructor function's prototype.

Source Code

Try it yourself

Code Explanation

In the above example, it is clear that the userInfo method is added to the constructor function prototype, and two objects namely person1 and person2 can access the prototype method userInfo.