Introduction
We have been hearing this term, Prototype Object, in JavaScript, and so on. But how does a Prototype Object play an important role in JavaScript? Let's try to understand that and implement it.
Definition
A Prototype Object is an object that simplifies the process of adding custom properties/methods to all instances of an object. Basically, in JavaScript, you are allowed to add custom properties to Prebuilt and Custom objects.
The following briefly describes Prebuilt and Custom Objects in JavaScript:
- Prebuilt: These are the objects that are created with the new keyword such as image, string, date, array object, and so on.
- Custom: These are the objects that are created by the developer to hold the properties or other information, for example:
- var Person = {};
When we talk about Object-Oriented Programming, we always think of how to create objects in JavaScript. Let's see some code in action to create and invoke objects in JavaScript.
- <script language="javascript" type="text/javascript">
- function Greet(mode) {
- this.mode = mode;
- this.callgreet = function() {
- alert( 'Good ' + this.mode)
- }
- }
- obj1 = new Greet("Morning")
- obj1.callgreet() //alerts "Good Morning"
- obj2 = new Greet("Evening")
- obj2.callgreet() //alerts "Good Evening"
- </script>
The approach that I will be taking is Prototyping that logically allows attachment of a method to an object after it's been defined. Let's see the code above re-structured in Prototype style.
- function Greet(mode) {
- this.mode = mode;
- this.callgreet = function() {
- alert( 'Good ' + this.mode)
- }
- }
- // Attaching changeGreet function with existing object using Prototype.
- Greet.prototype.changeGreet = function(greetmode){
- this.mode = greetmode;
- }
- obj1 = new Greet("Morning")
- obj1.callgreet() //alerts "Good Morning"
- obj2 = new Greet("Evening")
- obj2.callgreet() //alerts "Good Evening"
- obj2.changeGreet("Afternoon");
- obj2.callgreet();
- Easy to attach a new custom method to an object that is already defined/created.
- The new Custom Method is now shared/accessed by all instances of the object. In our case a new custom method (changeGreet) is accessible by obj1 and obj2.
I hope this article tried to explain the concept of prototyping, including how to use Prototyping to attach custom methods and properties.
Thanks for reading.

Ravi PatelPosted Apr 18, 2016, 5:42 AM
thanks for nice article
shanthi kumarPosted Sep 8, 2014, 2:42 AM
Very nice...
Guest UserPosted Sep 7, 2014, 11:57 PM
yeah Kamal .. prototype is very nice way for updating all instances of object.
Jeetendra GundPosted Sep 6, 2014, 5:39 AM
thanks sir...for sharing!