Understanding Prototype in JavaScript
The Prototype Chain
When you access a property on an object, JavaScript first looks at the object itself; if not found, it looks up the prototype chain until it finds the property or reaches null.
let arr = [1, 2, 3];
console.log(arr.__proto__ === Array.prototype); // true
Adding Methods via Prototype
Array.prototype.first = function() {
return this[0];
};
console.log([10, 20, 30].first()); // 10
Object.create()
let animal = { eats: true };
let rabbit = Object.create(animal);
console.log(rabbit.eats); // true, inherited via prototype
PreviousA Complete Guide to Prototypes in JavaScript: How They Work and Why They Matter
Next Restrict user to enter numeric value in textbox using javascript
Ready to master real-world JavaScript development?
Learn JavaScript hands-on with mentor-led, live sessions.