Prototype

The prototype is an object that every function gets automatically, as soon as you create it.

You can add properties and methods to the prototype property of your constructor function. Then all objects created with this constructor will have access to everything you add to the prototype.

var Person = function(name) {
  this.name = name;
};
Person.prototype.say = function() {
  return this.name;
};

if you add properties to the prototype of a "normal" function, meaning function that you don't invoke as a constructor, these will not be used.

Using the prototype

var adam = new Person('Adam');
alert(adam.name); // "Adam"
alert(adam.say()); // "Adam"

As you can see the object has access to the prototype’s members.

The prototype properties are shared among all objects.

Rule of thumb

And a general rule of thumb – the properties and methods that are meant to be reused and shared and inherited, should be added to the prototype.

Tags: ,

2 Responses to “Prototype”

  1. what is zocor Says:

    Great blog!! You should start many more. I love all the info provided. I will stay tuned :)

  2. vpsunmetered Says:

    Hmm is anyone else experiencing problems with the images on this blog loading? I’m trying to determine if its a problem on my end or if it’s the blog. Any feed-back would be greatly appreciated.

Leave a Reply