In addition to changing properties and methods, we can also use the prototype property. Every function has a prototype property that represents the prototype of the function.
For example, User.prototype represents the prototype of User objects. And any properties and methods that will be defined in User.prototype will be common to all User objects.
Consider an example:
//let's create a constructor of the Profile class function Profile(pName, pAge) { this.name = pName; this.age = pAge; this.displayInfo = function () { document.write("Name " + this.name + "; age: " + this.age); }; }; //let's create a hello prototype of the Profile class Profile.prototype.hello = function () { document.write(this.name + " say: Hello"); }; Profile.prototype.maxAge = 99; //let's create a maxAge prototype of the Profile class var alex = new Profile("Alexander", 33); //let's create an object of the Profile class alex.hello();//methods and functions specified in prototypes are available to all objects var john = new User("John", 28); john.hello(); console.log(alex.maxAge); // 99 console.log(john.maxAge); // 99
When accessing a property, javascript first looks for that property among the properties of the object, and if it was not found, then refers to the properties of the prototype. The same goes for methods.
Another example:
function Car(name, year) { this.name = name this.year = year } Car.prototype.getAge = function () { return new Date().getFullYear() - this.year } Car.prototype.color = 'black' var ford = new Car('Ford', 2015) var bmw = new Car('BMW', 2017) ford.color = 'red' console.log(ford) console.log(bmw)