MCQ Practice Single Best Answer Topic: Javascript Classes MCQ

Q The subclass that inherits the superclass may be expressed as follows if A is the superclass and B is the subclass:

Question ID
#4995
Subchapter
Javascript Classes MCQ
Action
Choose one option below

Choose Your Answer

Click an option to check whether your answer is correct.

  • A B=inherit(A);
  • B B=A.inherit();
  • C B.prototype=inherit(A);
  • D B.prototype=inherit(A.prototype);
Correct Answer: C

Explanation

In JavaScript, inheritance is implemented using prototypes, which are objects that serve as templates for creating other objects. There is no built-in inherit() function in JavaScript that allows one class to inherit from another, but you can achieve inheritance by setting up the prototype chain correctly.


To inherit from a superclass in JavaScript, you can use the Object.create() method to create a new object that has the superclass as its prototype. The new object will then inherit all of the properties and methods of the superclass.


For example:


function A() {
// Properties and methods of class A
}

A.prototype.sayHello = function() {
console.log('Hello from A');
}

function B() {
// Properties and methods of class B
}

// Set up inheritance
B.prototype = Object.create(A.prototype);

const b = new B();
b.sayHello(); // Output: "Hello from A"


Here, the B class is defined as a constructor function. The B prototype is then set to a new object that has the A prototype as its prototype using the Object.create() method.
This causes the B prototype to inherit all of the properties and methods of the A prototype, including the sayHello method. When we create a new B object using the new keyword, the object inherits the sayHello method from the B prototype, which in turn inherited it from the A prototype.

Share This Question

Share this MCQ with your friends or study group.