Object extension.prototype

In addition to directly defining properties and methods in the constructor, we can also use the prototype property. Every function has a prototype property that represents the prototype of the function. That is, the property User.prototype represents the prototype of User objects. And any properties and methods that are defined in User.prototype will be common to all User objects.

For example, after defining the User object, we needed to add a method and a property to it:

function User(pName, pAge) {
    this.name = pName;
    this.age = pageAge;
    this.displayInfo = function(){
        document.write("Name: " + this.name + "; age: " + this.age + "<br/>");
    };
};

User.prototype.hello = function(){
    document.write(this.name + " says 'Hi!'<br/>");
};
User.prototype.maxAge = 110;

var tom = new User("Tom", 26);
tom.hello();
var john = new User("John", 28);
john.hello();
console.log(tom.maxAge); // 110
console.log(john.maxAge); // 110

Here, a method hello and a property have been added maxAge, and each User object will be able to use them. But it is important to note that the value of the property maxAgewill is the same for all objects, it is a shared static property. As opposed to, say, a property like this.name that holds a value for a specific object.

At the same time, we can define a property in the object that will be named the same as the property of the prototype. In this case, the object’s own property will take precedence over the prototype property:

User.prototype.maxAge = 110;
var tom = new User("Tom", 26);
var john = new User("John", 28);
tom.maxAge = 99;
console.log(tom.maxAge); // 99
console.log(john.maxAge); // 110

And when accessing the maxAge property, javascript first looks for this property among the properties of the object, and if it was not found, then it accesses the properties of the prototype. The same goes for methods.