Problem Statement
What is the prototype in JavaScript?
Explanation
A prototype is an object from which other objects inherit properties and methods.
Every JavaScript object has a hidden property called prototype that points to another object.
When you access a property on an object, JavaScript first looks on the object itself. If not found, it looks in the prototype. This continues up the chain until the property is found or the chain ends.
Functions have a prototype property that is used when creating objects with the new keyword.
Prototypes enable inheritance in JavaScript without classes, though ES6 classes use prototypes under the hood.
Understanding prototypes is crucial for mastering JavaScript.
Code Solution
SolutionRead Only
// Every object has a prototype
const obj = {};
console.log(Object.getPrototypeOf(obj)); // Object.prototype
// Function prototype property
function Person(name) {
this.name = name;
}
Person.prototype.greet = function() {
console.log('Hello, ' + this.name);
};
const john = new Person('John');
john.greet(); // 'Hello, John'
// john doesn't have greet directly
console.log(john.hasOwnProperty('greet')); // false
console.log(john.hasOwnProperty('name')); // true
// greet comes from prototype
console.log(john.__proto__ === Person.prototype); // true
// Prototype chain
const arr = [1, 2, 3];
// arr -> Array.prototype -> Object.prototype -> null
console.log(arr.__proto__ === Array.prototype); // true
console.log(arr.__proto__.__proto__ === Object.prototype); // true
// Adding to prototype affects all instances
Person.prototype.sayBye = function() {
console.log('Bye, ' + this.name);
};
john.sayBye(); // 'Bye, John' (new method available)