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.class Person {
constructor(fname, lname) {
this.fname = fname;
this.lname = lname;
}
static favColor() {
return 'blue';
}
get firstName() {
return this.fname;
}
sayName() {
console.log(`${this.fname} ${this.lname}`);
}
}
const person1 = new Person('John', 'Doe');
person1.sayName();
console.log(person1.firstName);
console.log(person1.favColor);
console.log(Person.favColor());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.class Person {
constructor(fname, lname) {
this.fname = fname;
this.lname = lname;
}
get firstName() {
return this.fname;
}
}
// inspect where 'firstName' lives without creating an instanceRewrite 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.class Person {
constructor(fname, lname) {
this.fname = fname;
this.lname = lname;
}
// turn favColor into a static getter that returns 'blue'
}
console.log(Person.favColor);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.class Person {
constructor(fname, lname) {
this.fname = fname;
this.lname = lname;
}
static favColor() {
return 'blue';
}
get firstName() {
return this.fname;
}
}
class Employee extends Person {}
console.log(Employee.favColor());
console.log(new Employee('Ada', 'L').firstName);