All sample questions / JavaScript
JavaScript this, Prototypes and Classes, what does console.log(c.area()) print after function Shape() {}?
Block 3, this, Prototypes and Classes, question 15 of the JavaScript sample
function Shape() {}
Shape.prototype.area = function() { return 0; };
function Circle(radius) {
this.radius = radius;
}
Object.assign(Circle.prototype, Shape.prototype, {
area() { return this.radius * this.radius * 3; }
});
const c = new Circle(2);
console.log(c.area());
What does this print?
Show the answer and why each option is right or wrong
Answer, A. 12
- A. 12
- Correct. Object.assign copies properties left to right, so the area method from the plain object argument overwrites the one copied earlier from Shape.prototype, and that final version reads radius.
- B. undefined
- Assumes none of the sources properties actually get copied onto Circle.prototype, leaving area unset. Object.assign genuinely copies own enumerable properties from each source object onto the target, area does end up defined on Circle.prototype by the end of the call.
- C. 0
- Assumes the first area definition encountered among the sources, the one from Shape.prototype, is the one that survives on Circle.prototype. Object.assign copies each source object properties in order, later sources overwrite properties of the same name from earlier sources, so the last area definition wins.
- D. TypeError
- Assumes calling the copied method later on a Circle instance is disallowed because it was attached through Object.assign rather than directly in a class or prototype assignment. A method copied onto a prototype through Object.assign behaves exactly like any other prototype method once it is there, it is called normally through instances.
Object.assign copies properties from its source arguments onto the target object in order, and when multiple sources define the same property name, the one from the later source argument wins. Here Shape.prototype area is copied first, then overwritten by the area defined in the final plain object argument, since it comes after Shape.prototype in the argument list. Calling c.area() therefore runs that final version, computing 2 times 2 times 3.
The answer above is what the Node interpreter printed when the snippet was run, not what someone expected it to do.
This question comes from a bank of 600 JavaScript interview questions, all built the same way, sold as one PDF with the full answer key.
Get the 600 JavaScript questions, 9 euros
Or play the free JavaScript sample, twenty questions in the browser, also as a free PDF.
Previous question Next question
Did this save you a lookup? Buy me a coffee on Ko-fi.