Unlike classical object-oriented languages (like Java or C++), JavaScript uses Prototypal Inheritance. Every object in JavaScript has an internal link to another object called its prototype.
How Prototype Property Lookup Works
When accessing a property on an object:
1. JavaScript checks if the property exists directly on the object (own property).
2. If not found, it traverses up the [[Prototype]] link to the parent prototype object.
3. This traversal continues until the property is found or null is reached (end of the chain).
const parent = {
greet() {
return `Hello from ${this.name}`;
}
};
const child = Object.create(parent);
child.name = "Alice";
console.log(child.greet()); // "Hello from Alice" (inherited method)
console.log(child.hasOwnProperty("name")); // true
console.log(child.hasOwnProperty("greet")); // falseES6 class vs Prototypal Constructor Functions
ES6 class syntax is syntactic sugar built on top of prototypal inheritance.
// ES6 Class
class Animal {
constructor(name) {
this.name = name;
}
speak() {
return `${this.name} makes a sound.`;
}
}
// Equivalent ES5 Constructor Function
function AnimalES5(name) {
this.name = name;
}
AnimalES5.prototype.speak = function () {
return this.name + " makes a sound.";
};Practice Prototypal Exercises Live
Conduct Live Coding Interviews in the Browser
No candidate sign-up required. Create a room, share the link, and code together in real time with shared code execution.