English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

JavaScript Basic Tutorial

JavaScript Objects

JavaScript Functions

JS HTML DOM

JS Browser BOM

AJAX Basic Tutorial

JavaScript Reference Manual

JavaScript Object Prototype

PrototypeIt is a mechanism by which JavaScript objects inherit features from each other.

In the previous chapter, we learned how to useConstructor:

function User(fname, lname, age, loc) {
   this.firstName = fname;
   this.lastName = lname;
   this.age = age;
   this.location = loc;
}
var Seagull = new User("Seagull", "Anna", 22, "New Delhi");
var tarush = new User("Tarush", "Balodhi", 34, "Bihar");
Test and see‹/›

We also learned thatCannotAdd the new property to the existing object constructor:

User.weapon = "Sword";
Test and see‹/›

To add a new property to the constructor, it must be added to the constructor itself:

function User(fname, lname, age, loc) {
   this.firstName = fname;
   this.lastName = lname;
   this.age = age;
   this.location = loc;
   this.weapon = "Sword";
}
Test and see‹/›

Sometimes we want to add new properties and methods to a constructor later, which will be shared among all objects (examples). The answer is the objectPrototype.

Using the Prototype Property

The prototype property allows you to add properties and methods to the constructor.

In this example, the prototype property allows you to add new properties to the User object constructor:

function User(fname, lname, age, loc) {
   this.firstName = fname;
   this.lastName = lname;
   this.age = age;
   this.location = loc;
}
User.prototype.weapon = "Sword";
Test and see‹/›

In this example, the prototype property allows you to add new methods to the User object constructor:

function User(fname, lname, age, loc) {
   this.firstName = fname;
   this.lastName = lname;
   this.age = age;
   this.location = loc;
}
User.prototype.fullName = function() {
return this.firstName + " " + this.lastName;
};
Test and see‹/›

Note:Only modify your own prototype. Do not modify the prototype of standard (built-in) JavaScript objects.