Skip to main content

Prototypal Inheritance

Prototypes / Inheritance: Prototypal Inheritance



What does a prototype refer to in JavaScript?

View Answer:
Interview Response: A prototype in JavaScript is an object that other objects inherit properties and methods, enabling code reusability and efficient memory usage.

Technical Response: Objects in JavaScript feature a special hidden property called [[Prototype]] (as defined in the standard), which is either null or refers to another object. We refer to this object as a prototype. JavaScript objects inherit features from one another through the use of prototypes. Objects can have a prototype object, which acts as a template object from which it inherits methods and properties to provide inheritance. JavaScript commonly gets described as a prototype-based language.

Code Example:

Overview: Historical example using proto, which is now deprecated (no longer supported)

let animal = {
eats: true,
};
let rabbit = {
jumps: true,
};

rabbit.__proto__ = animal; // (*) __proto__ deprecated

// we can find both properties in rabbit now:
console.log(rabbit.eats); // true (**)
console.log(rabbit.jumps); // true

note

You should be familiar with the __proto__ because you may see it in older code.


What exactly is a prototype in JavaScript when it comes to objects?

View Answer:
Interview Response: A prototype in JavaScript is an object serving as a blueprint for other objects to inherit properties and methods, promoting code reusability and memory efficiency.

Technical Response: A prototype is a fixed entity called an object. When you declare a function, it generates a prototype related to it. Furthermore, the prototype object establishes a link to its function, resulting in a circular relationship. This behavior applies to any function. Objects get created in various ways in JavaScript, and the new keyword is one method. We apply an uppercase initial letter to the function name when we declare it if we intend on utilizing the "new" keyword. (a constructor function).

Code Example:

// Prototypal Inheritance
function User(name) {
this.name = name;
this.isAdmin = false;
}

let user = new User('Jack');

console.log(user.name); // Jack
console.log(user.isAdmin); // false
console.log(user instanceof User); // true

In JavaScript prototypal inheritance, what is the value of the “this” keyword?

View Answer:
Interview Response: In JavaScript prototypal inheritance, the "this" keyword refers to the instance of the object on which a method is called, enabling access to its properties and methods.

Code Example:

// animal has methods
let animal = {
walk() {
if (!this.isSleeping) {
console.log(`I am walking`);
}
console.log("I'm asleep!");
},
sleep() {
this.isSleeping = true;
},
};

animal.walk(); // returns 'I am walking'

let rabbit = {
name: 'White Rabbit',
__proto__: animal,
};

// modifies rabbit.isSleeping
rabbit.sleep();

console.log(rabbit.isSleeping); // true
console.log(animal.isSleeping); // undefined (no such property)

note

Prototypes do not affect "this", regardless of the method the location in an object or prototype. This structure is always the object before the dot in a method call.


Can you explain the difference between Object.create() and the new keyword in relation to prototypal inheritance?

View Answer:
Interview Response: `Object.create(proto)` directly sets `proto` as the prototype of a new object, whereas `new Constructor()` creates an object with `Constructor.prototype` as its prototype.

Code Example:

// Using Object.create()
let proto = { name: "Proto" };
let obj = Object.create(proto);
console.log(obj.name); // "Proto"

// Using new keyword
function Constructor() { this.name = "Constructor"; }
let newObj = new Constructor();
console.log(newObj.name); // "Constructor"

How does JavaScript implement inheritance compared to classical inheritance in other languages?

View Answer:
Interview Response: JavaScript implements inheritance through prototypal inheritance, where objects inherit properties and methods directly from other objects. Classical inheritance uses classes to define and inherit behavior.

What is the difference between a prototype and a constructor in JavaScript?

View Answer:
Interview Response: In JavaScript, a prototype is an object used for inheritance, while a constructor is a function that creates new instances of objects and initializes their properties and methods.

Code Example:

// Constructor
function Car(make, model) {
this.make = make;
this.model = model;
}

// Create a new object using the Car constructor
let car1 = new Car('Toyota', 'Corolla');
console.log(car1.make); // Output: Toyota
console.log(car1.model); // Output: Corolla

// Prototype
Car.prototype.getDetails = function() {
return this.make + ' ' + this.model;
}

// Use the prototype method
console.log(car1.getDetails()); // Output: Toyota Corolla

In the above example, Car is a constructor function. We use this constructor to create car1. We then add a method getDetails to Car.prototype. Now every object created with new Car() will have access to getDetails.


What is the prototype chain, and how does it work in JavaScript?

View Answer:
Interview Response: The prototype chain in JavaScript is a series of linked prototypes from which objects inherit properties and methods. It enables property lookups through parent prototypes until found or undefined.

How can you create a new object that inherits from another object in JavaScript?

View Answer:
Interview Response: We can create a new object that inherits from another by using Object.create() with the desired object as the prototype or by setting the constructor's prototype.

Code Example:

let decoration = {
color: 'red',
};

let rose = Object.create(decoration);
console.log(rose.color) // rose color: red

Can you explain the role of the "this" keyword in prototypal inheritance?

View Answer:
Interview Response: In prototypal inheritance, "this" refers to the instance object, allowing access to its properties and methods. It enables sharing and reuse of code across objects in a prototype chain.

How does the for-in loop handle inherited properties?

View Answer:
Interview Response: The for-in loop iterates over an object's enumerable properties, including inherited ones from its prototype chain. It doesn't differentiate between own and inherited properties, accessing all enumerable keys.

Code Example:

let decoration = {
color: 'red',
};

let circle = Object.create(decoration);
circle.radius = 10;

for (const prop in circle) {
console.log(prop);
}

// Returns radius, color

Code Example: The Old __proto__

let animal = {
eats: true,
};

let rabbit = {
jumps: true,
__proto__: animal,
};

for (let prop in rabbit) {
let isOwn = rabbit.hasOwnProperty(prop);

if (isOwn) {
console.log(`Our: ${prop}`); // Our: jumps
} else {
console.log(`Inherited: ${prop}`); // Inherited: eats
}
}

danger

The proto notation is not recommended in JavaScript because it is deprecated. The proto notation is a way of creating objects that inherit from other objects. However, the proto notation is not as efficient as other methods of creating objects, and it can be difficult to use. Therefore, it is recommended to use other methods of creating objects, such as the constructor function.


What are some advantages and disadvantages of using prototypal inheritance in JavaScript?

View Answer:
Interview Response: Advantages: flexibility, memory efficiency, easy object creation. Disadvantages: readability issues, inadvertent property/method sharing, and potential performance impact due to longer prototype chains.

How do you prevent an object from inheriting properties from its prototype?

View Answer:
Interview Response: To prevent inheritance, create an object with null as its prototype using Object.create(null). This results in an object without a prototype, so it won't inherit properties or methods from any prototype chain.

Code Example:

let obj = Object.create(null);

// Try to use a method from Object.prototype
console.log(obj.toString); // Output: undefined

In the above example, obj doesn't have access to toString method from Object.prototype as it was created with no prototype.