Question Bank
/

JavaScript Class Static vs Instance: Two Explanations Quiz

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.

Question Bank
Medium
JavaScript
4 questions
quiz
classes
js-prototypes
js-language

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());