Prototype in JavaScript
Objective- Understanding the prototype in JavaScript with the help of examples
Prototypes are the mechanism by which JavaScript objects inherit features from one another.
prototype property of Javascript allows you to add new properties and methods to objects
function Person () {
this.name = 'Rahul',
this.lastname = 'Dev'
}
const person = new Person(); // a constructor function
We cannot add a new property to an existing object constructor
Person.nationality = "Indian";
console.log(person.nationality); //undefined
Adding a new property Person.nationality will show an undefined
So, prototype property of Javascript allows you to add new properties and methods to objects
Person.prototype.nationality = "Indian";
OR
Person.prototype.fullname = function() {
return this.name + " " + this.lastname;
};
Now, Person Object will change to,
function Person () {
this.name = 'Rahul',
this.lastname = 'Dev',
this.nationality = 'Indian',
this.fullname = function() {
return this.name + " " + this.lastname;
};
}
const person = new Person();
console.log(person.nationality); // Indian
All the objects in JavaScript, inherit the properties and methods from Object.prototype
Example,
const myclass=['first', 'second'];
Object.prototype.newclass= function(){
console.log("third class is not present");
}
Object.prototype.missingclass='third';
myclass.newclass() //third class is not present
console.log(newclass.missingclass); //third -> (property access from the global object)
Remember, we cannot add myclass.prototype.newclass=function (){....} as myclass is not object constructor