JavaScript Prototype
JavaScript is a prototype-based language that allows objects to inherit properties and methods from other objects. Each object in JavaScript has an internal link to another object called its prototype. This enables inheritance and method sharing among objects.
Key Features of JavaScript Prototype
- Every JavaScript function automatically has a
prototype
property that is used to implement inheritance. - All JavaScript objects inherit properties and methods from their prototype.
- Prototypes enable the reusability of methods, reducing memory usage by sharing methods across instances.
You can add methods or properties to a function's prototype using the syntax:
Prototype Syntax
Syntax
ConstructorFunction.prototype.propertyName = value;
ConstructorFunction.prototype.methodName = function() {
// method body
};
Code Example: Adding Methods with Prototype
Example 1
function Person(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
// Adding a method to the prototype
Person.prototype.getFullName = function() {
return this.firstName + " " + this.lastName;
};
// Creating objects
const person1 = new Person("John", "Doe");
const person2 = new Person("Jane", "Smith");
console.log(person1.getFullName()); // Output: John Doe
console.log(person2.getFullName()); // Output: Jane Smith
Output
John Doe
Jane Smith
Explanation
- The
Person
constructor function initializes thefirstName
andlastName
properties. - The
getFullName()
method is added to the prototype of thePerson
function, allowing all instances ofPerson
to share the method. - This approach avoids creating a separate copy of the method for each instance, saving memory.
Example: Adding Properties with Prototype
Example 2
function Car(make, model) {
this.make = make;
this.model = model;
}
// Adding a property to the prototype
Car.prototype.type = "Sedan";
// Creating objects
const car1 = new Car("Toyota", "Camry");
const car2 = new Car("Honda", "Accord");
console.log(car1.make + " " + car1.model + " " + car1.type);
console.log(car2.make + " " + car2.model + " " + car2.type);
output
Toyota Camry Sedan
Honda Accord Sedan
Prototype Chaining
In JavaScript, objects can inherit properties and methods through prototype chaining. If a property or method is not found on the object, the JavaScript engine looks for it in the object's prototype, and so on up the chain.
Example: Prototype Chain
Example 3
function Animal(type) {
this.type = type;
}
Animal.prototype.eat = function() {
console.log(this.type + " is eating");
};
function Dog(name) {
Animal.call(this, "Dog");
this.name = name;
}
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;
Dog.prototype.bark = function() {
console.log(this.name + " is barking");
};
// Creating an instance
const dog = new Dog("Buddy");
dog.eat(); // Output: Dog is eating
dog.bark(); // Output: Buddy is barking
output
Dog is eating
Buddy is barking