JavaScript Prototypes & Constructor Functions: Prototypal Inheritance, Prototype Chain & Examples
1. What is a prototype in JavaScript?
Q: What is a prototype in JavaScript?
A prototype is an object from which other objects inherit properties and methods. Every JavaScript object has a prototype, accessible via the __proto__ property or Object.getPrototypeOf(). Prototypes enable inheritance and shared behavior.
2. What is the prototype chain?
Q: What is the prototype chain?
The prototype chain is a series of linked prototype objects that JavaScript traverses to find a property or method. If a property isn't found on an object, JavaScript looks at its prototype, then the prototype's prototype, until it reaches Object.prototype or null.
3. How can you access an object's prototype?
Q: How to access an object's prototype?
Use the __proto__ property (non-standard but widely supported) or Object.getPrototypeOf(object). Example:
let obj = {};
console.log(Object.getPrototypeOf(obj) === Object.prototype); // true
4. What is the role of Object.prototype?
Q: Role of Object.prototype?
Object.prototype is the root of all prototype chains in JavaScript. It provides default methods like toString(), hasOwnProperty(), and valueOf() that all objects inherit.
5. What happens when you add a property to a prototype?
Q: Adding property to prototype?
Adding a property to a prototype makes it available to all objects that inherit from that prototype, unless the object has its own property of the same name (shadowing). Example:
function Person() {}
Person.prototype.greet = function() { return "Hello"; };
let person = new Person();
console.log(person.greet()); // Output: Hello
6. What is prototypal inheritance in JavaScript?
Q: What is prototypal inheritance?
Prototypal inheritance is JavaScript's mechanism for objects to inherit properties and methods from other objects via their prototype. When an object accesses a property, JavaScript looks up the prototype chain to find it.
7. How does prototypal inheritance differ from classical inheritance?
Q: Prototypal vs classical inheritance?
- Prototypal inheritance: Objects inherit directly from other objects via prototypes (dynamic, flexible).
- Classical inheritance: Classes inherit from other classes (e.g., in languages like Java), using a rigid, class-based structure. JavaScript mimics classical inheritance with
classsyntax but uses prototypes under the hood.
8. How do you implement prototypal inheritance?
Q: Implementing prototypal inheritance?
Create an object and set its prototype to another object using Object.create() or constructor functions. Example with Object.create():
let animal = {
speak: function() {
return `${this.name} makes a sound`;
}
};
let dog = Object.create(animal); // dog inherits from animal
dog.name = "Rex";
console.log(dog.speak()); // Output: Rex makes a sound
console.log(Object.getPrototypeOf(dog) === animal); // true
9. What is the benefit of prototypal inheritance?
Q: Benefits of prototypal inheritance?
- Saves memory by sharing methods across instances.
- Allows dynamic addition of properties/methods to prototypes.
- Enables flexible object relationships without rigid class hierarchies.
10. What are some pitfalls of prototypal inheritance?
Q: Pitfalls of prototypal inheritance?
- Shared prototype issues: Modifying a prototype affects all instances (e.g., adding a method to
Array.prototypeaffects all arrays). - Overwriting properties: Child objects can accidentally shadow inherited properties.
- Complexity in deep prototype chains: Can make debugging harder.
11. How do you check if a property is inherited or own?
Q: Check own vs inherited property?
Use object.hasOwnProperty("property") to check if a property belongs to the object itself, not its prototype. Example:
let obj = Object.create({ inherited: "from prototype" });
obj.own = "own property";
console.log(obj.hasOwnProperty("own")); // true
console.log(obj.hasOwnProperty("inherited")); // false
12. What is a constructor function in JavaScript?
Q: What is a constructor function?
A constructor function is a special function used to create and initialize objects. It's called with the new keyword, setting the new object's prototype to the constructor's prototype property. Example:
function Person(name) {
this.name = name;
}
let person = new Person("Alice");
13. How does the new keyword work with constructor functions?
Q: How does the new keyword work?
The new keyword:
- Creates a new empty object.
- Sets the object's prototype to the constructor's
prototypeproperty. - Binds
thisto the new object and executes the constructor. - Returns the new object (unless the constructor returns another object).
14. Can you give an example of a constructor function with prototype methods?
Q: Constructor with prototype methods example?
function Person(name, age) {
this.name = name;
this.age = age;
}
// Add method to prototype
Person.prototype.greet = function() {
return `Hello, I'm ${this.name}!`;
};
let alice = new Person("Krishna", 24);
let bob = new Person("Kristal", 23);
console.log(alice.greet()); // Output: Hello, I'm Krishna!
console.log(bob.greet()); // Output: Hello, I'm Kristal!
console.log(Object.getPrototypeOf(alice) === Person.prototype); // true
15. How do you implement inheritance with constructor functions?
Q: Inheritance with constructor functions?
Use constructor functions and set the prototype of the child constructor to an instance of the parent constructor. Example:
function Animal(name) {
this.name = name;
}
Animal.prototype.speak = function() {
return `${this.name} makes a sound`;
};
function Dog(name, breed) {
Animal.call(this, name); // Inherit properties
this.breed = breed;
}
// Inherit prototype
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog; // Fix constructor reference
Dog.prototype.bark = function() {
return `${this.name} barks!`;
};
let dog = new Dog("Rex", "Labrador");
console.log(dog.speak()); // Output: Rex makes a sound
console.log(dog.bark()); // Output: Rex barks!
console.log(dog instanceof Dog); // true
console.log(dog instanceof Animal); // true
16. What is the constructor property in prototypes?
Q: What is the constructor property?
The constructor property in a prototype points to the constructor function used to create an object. It's used to maintain the link between an object and its constructor (e.g., dog.constructor === Dog).
17. What are the advantages of using constructor functions?
Q: Advantages of constructor functions?
- Provide a reusable blueprint for creating objects.
- Allow shared methods via the prototype, saving memory.
- Support inheritance for creating hierarchies of objects.
18. What are the limitations of constructor functions?
Q: Limitations of constructor functions?
- Can be verbose compared to ES6
classsyntax. - Requires careful management of prototype chains to avoid errors.
- Forgetting to use
newcan lead to bugs, asthisbinds to the global object.
19. How does the ES6 class syntax relate to constructor functions?
Q: ES6 class vs constructor functions?
The ES6 class syntax is syntactic sugar over constructor functions and prototypes. It provides a cleaner way to define constructors and inheritance but uses the same prototypal inheritance under the hood. Example:
class Person {
constructor(name) {
this.name = name;
}
greet() {
return `Hello, I'm ${this.name}!`;
}
}
let person = new Person("Alice");
console.log(person.greet()); // Output: Hello, I'm Alice!
20. What happens if you call a constructor function without new?
Q: Calling constructor without new?
Without new, this refers to the global object (e.g., window in browsers), which can cause unintended behavior or errors. Always use new with constructor functions.