Question Bank
JavaScript Inherit x From Function b: Two Approaches Quiz
Difficulty: Medium
Make constructor `b` inherit `x` from constructor `a`: parent-constructor call via `Function.prototype.call`, ES6 `extends` + `super`, `Object.create` chaining, and an arrow-vs-constructor explainer.
JavaScript Inherit x From Function b: Two Approaches Quiz
Make constructor `b` inherit `x` from constructor `a`: parent-constructor call via `Function.prototype.call`, ES6 `extends` + `super`, `Object.create` chaining, and an arrow-vs-constructor explainer.
705 views
4
Modify constructor b below so that calling new b(1, 2) produces an instance with BOTH y: 2 and x: 1. Use Function.prototype.call to invoke a with this bound to the new b instance.
Examples
Example 1:
Input:
const a = function (x) { this.x = x; };
const b = function (x, y) { this.y = y; };
const result = new b(1, 2);
Output before fix: b { y: 2 }
Output after fix: b { y: 2, x: 1 }
Explanation: a.call(this, x) wires a's assignment onto b's instance.Rewrite the same a/b relationship as ES6 classes: class A { constructor(x) { this.x = x; } }, class B extends A { constructor(x, y) { ... } }. Use super(x) to forward the assignment.
Examples
Example 1:
Input: new B(1, 2)
Output: B { x: 1, y: 2 }
Explanation: super(x) runs A's constructor with this bound to the new B instance.Without using class, wire b.prototype = Object.create(a.prototype) so that an instance built with new b(1, 2) also inherits any future methods added to a.prototype. Demonstrate by adding a.prototype.describe and calling it on a b instance.
Examples
Example 1:
Input:
a.prototype.describe = function () { return 'x=' + this.x; };
const i = new b(1, 2);
i.describe();
Output: 'x=1'
Explanation: b inherits a's prototype chain, so describe is reachable on b instances.Explain why writing const Bar = () => {} and then calling new Bar() throws TypeError: Bar is not a constructor. In a short code block, show ONE arrow-function trait that disqualifies it from being used with new.
