JavaScript Prototype
Syntax
objectName.prototype.propertyName = value;
Example
function Person(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
Person.prototype.fullName = function() {
return this.firstName + " " + this.lastName;
};
var person1 = new Person("John", "Doe");
console.log(person1.fullName()); // Output: John Doe
Output
John Doe
Explanation
In JavaScript, every object has a prototype
property that allows us to add properties and methods to that object. Prototype
is a way to create objects that share properties and methods. It is like a blueprint for creating objects.
In the above example, we have created a Person
constructor function that takes firstName
and lastName
as parameters. We have added a fullName
method to the Person
prototype which returns the full name of the person.
We have then instantiated a person1
object and called the fullName
method on it to get the full name of the person.
Use
JavaScript prototype is used to add properties and methods to an object such that all objects that are created using the constructor function share the properties and methods defined in the prototype.
Important Points
- Every object has a
prototype
property that allows us to add properties and methods to that object. Prototype
is a way to create objects that share properties and methods.- Prototypes are used to add properties and methods to objects created using constructor functions.
- Always define methods on the prototype object to save memory space and improve performance.
Summary
In JavaScript, prototype is a way to add properties and methods to objects. It is a blueprint for creating objects that share properties and methods. We can add properties and methods to objects by setting them on the prototype
property of the object's constructor function. Using prototypes helps to save memory space and improve performance.