JavaScript Prototypes and Classes 4 — Questions and Answers
Question 1: What is the prototype of a regular function's prototype object (e.g., `function Foo(){}`)?
- null
- Function.prototype
- Object.prototype (Correct answer)
- Foo
Correct answer: Object.prototype
By default, a function's `.prototype` object inherits from `Object.prototype`, just like any regular object.
Question 2: What is the purpose of `Object.setPrototypeOf(obj, proto)`?
- Freeze an object's prototype
- Set the prototype of obj to proto at runtime (Correct answer)
- Create a new object inheriting from proto
- Seal the object
Correct answer: Set the prototype of obj to proto at runtime
`Object.setPrototypeOf()` changes the `[[Prototype]]` of an existing object, though it is discouraged for performance reasons.
Question 3: Which accessor type allows you to run logic when a class property is read?
- setter
- getter (Correct answer)
- accessor
- proxy
Correct answer: getter
A `get` accessor (getter) runs a function when the property is accessed and returns its return value.
Question 4: What does `instanceof` check?
- Whether two objects share the same reference
- Whether an object's prototype chain includes the constructor's prototype (Correct answer)
- Whether an object was created with `new`
- Whether a class is a subclass of another
Correct answer: Whether an object's prototype chain includes the constructor's prototype
`instanceof` checks if `Constructor.prototype` exists anywhere in the object's prototype chain.
Question 5: What happens if you call a class constructor without the `new` keyword?
- It returns undefined
- It returns the global object
- It throws a TypeError (Correct answer)
- It works just like a regular function
Correct answer: It throws a TypeError
Classes enforce being called with `new`; calling them without it throws a `TypeError: Class constructor cannot be invoked without 'new'`.
Question 6: What is `Object.prototype.__proto__`?
- Object.prototype itself
- null (Correct answer)
- Function.prototype
- undefined
Correct answer: null
`Object.prototype` is the top of the prototype chain, and its `__proto__` is `null`, ending the chain.
Question 7: Which of the following is true about static class fields?
- They are inherited by instances
- They are shared across all instances via the prototype
- They belong to the class itself, not instances (Correct answer)
- They must be declared inside the constructor
Correct answer: They belong to the class itself, not instances
Static fields belong to the class object directly and are not accessible on instances, only via the class name.
What is the prototype of a regular function's prototype object (e.g., `function Foo(){}`)?