• Tutorials Logic, IN
  • +91 8092939553
  • info@tutorialslogic.com

Prototypes in JavaScript

Prototypes

Prototype in JavaScript is one of the most important concepts that every JavaScript developer must know. In this tutorial, we will discuss what are prototypes in JavaScript, and how they help JavaScript in achieving the concepts of Object Oriented Programming. To understand this tutorial, you must understand the JavaScript classes and objects.

Conventional JavaScript doesn't have class instead it has prototypes. Whenever we create a function using JavaScript, then JavaScript engine adds a prototype property inside a function, and this prototype property is known as the Prototype object. We can easily attach methods and properties to a prototype object, which enables all the other objects to inherit these methods and properties.

										    
											function Student() {
												this.name = 'Uttam';
												this.gender = 'Male';
											}
											
											var studentObject1 = new Student();
											studentObject1.age = 25;
											console.log(studentObject1.age); // 25
											
											var studentObject2 = new Student();
											console.log(studentObject2.age); // undefined
											
										

In the above example, age property is attached to studentObject1 instance, so studentObject2 instance will not have age property because it is defined only on studentObject1 instance. If we want to add new properties at later stage to a function which will be shared across all the instances, then we have set the properties using prototype.

										    
											function Student() {
												this.name = 'Uttam';
												this.gender = 'Male';
											}
											
											Student.prototype.age = 25;
											
											var studentObject1 = new Student();
											console.log(studentObject1.age); // 25
											
											var studentObject2 = new Student();
											console.log(studentObject2.age); // 25