Question Bank
JavaScript Class Static vs Instance: Two Explanations Quiz
Difficulty: Medium
Two seeded explanations of how a `Person` class with a static method, a getter, and an instance method behaves when called via `new`, plus two companions on getter syntax and static field inheritance.
JavaScript Class Static vs Instance: Two Explanations Quiz
Two seeded explanations of how a `Person` class with a static method, a getter, and an instance method behaves when called via `new`, plus two companions on getter syntax and static field inheritance.
1,124 views
26
Predict the four lines printed by the snippet below and explain why person1.favColor is undefined.
Examples
Example 1:
Input: the snippet in `code` is executed end-to-end
Output:
John Doe
John
undefined
blue
Explanation: sayName logs the full name, the firstName getter returns the private fname, favColor is a static method so it is not on instances, and Person.favColor() invokes the static method directly.Where does the firstName getter actually live in the prototype chain, and how can you confirm it without instantiating Person? Demonstrate with Object.getOwnPropertyDescriptor.
Examples
Example 1:
Input: Object.getOwnPropertyDescriptor(Person.prototype, 'firstName')
Output: { get: [Function: get firstName], set: undefined, enumerable: false, configurable: true }
Explanation: getters are installed on the class prototype, not on instances, with non-enumerable, configurable descriptors.Rewrite the Person class so favColor is a static getter instead of a static method, then show how to read it without parentheses.
Examples
Example 1:
Input: Person.favColor
Output: blue
Explanation: a static getter exposes a property-style read on the class itself, so no call-parentheses are needed.Predict the output when Employee extends Person and a subclass instance accesses both the inherited static method and the inherited getter.
Examples
Example 1:
Input:
class Employee extends Person {}
console.log(Employee.favColor());
console.log(new Employee('Ada', 'L').firstName);
Output:
blue
Ada
Explanation: static methods and prototype accessors both flow through the extends chain, so the subclass inherits both.