Every JavaScript object has a prototype. The prototype is also an object. All JavaScript objects inherit their properties and methods from their prototype.
In the previous lesson, we learned about constructors. If you want to add a new property (or method) to a constructor, you have to add it to the constructor function definition itself. But what if the constructor is from a third-party library or you want to add something later? That's where Prototypes come in.
The prototype property allows you to add new properties and methods to object
constructors:
function Person(first, last, age) {
this.firstName = first;
this.lastName = last;
this.age = age;
}
Person.prototype.nationality = "Bangladeshi";
Person.prototype.greet = function() {
return "Hello, I am " + this.firstName;
};
When you try to access a property or method on an object, JavaScript first looks at the object itself. If it doesn't find it there, it looks at the object's prototype. This continues until it finds the property or reaches the end of the chain (null).
You can even add new methods to built-in JavaScript objects like Array or
String. However, this is generally discouraged because it
can lead to conflicts with other libraries or future versions of JavaScript.
// Adding a method to the built-in String prototype
String.prototype.sayHi = function() {
return "Hi " + this;
};
"Mim".sayHi(); // "Hi Mim"
prototype property to extend existing
constructors__proto__ in code