JavaScript Prototypes and Classes 3 — Questions and Answers
Question 1: What does the `hasOwnProperty()` method check?
- Whether the object exists in the prototype chain
- Whether a property exists directly on the object (not inherited) (Correct answer)
- Whether the object has a constructor
- Whether a method is static
Correct answer: Whether a property exists directly on the object (not inherited)
`hasOwnProperty()` returns `true` only if the property belongs directly to the object, not inherited via the prototype chain.
Question 2: What is the value of `Animal.prototype.constructor` after `class Animal {}`?
- undefined
- Object
- Animal (Correct answer)
- Function
Correct answer: Animal
By default, `prototype.constructor` points back to the class (or function) itself.
Question 3: Private class fields in JavaScript are declared with which prefix?
- _
- __
- # (Correct answer)
- @
Correct answer: #
The `#` prefix declares a truly private field that is only accessible within the class body.
Question 4: What does `class B extends A {}` set as `B.prototype`'s prototype?
- Object.prototype
- A
- A.prototype (Correct answer)
- B
Correct answer: A.prototype
When extending a class, `B.prototype` is given `A.prototype` as its prototype, establishing the inheritance chain.
Question 5: Which of the following correctly overrides a parent method in a subclass?
- Define a method with the same name in the subclass (Correct answer)
- Use `override` keyword before the method
- Call `super.remove(methodName)`
- Reassign `Parent.prototype.method`
Correct answer: Define a method with the same name in the subclass
Defining a method with the same name in the subclass shadows the parent's version due to prototype chain lookup order.
Question 6: What is the output of: `class A { greet() { return 'A'; } } class B extends A { greet() { return super.greet() + 'B'; } } console.log(new B().greet());`?
- 'A'
- 'B'
- 'AB' (Correct answer)
- TypeError
Correct answer: 'AB'
`super.greet()` calls `A`'s `greet()` returning `'A'`, then `'B'` is appended, producing `'AB'`.
Question 7: Which statement about class declarations is true?
- They are hoisted with initialization
- They are not hoisted at all
- They are hoisted but not initialized (temporal dead zone) (Correct answer)
- They behave exactly like function declarations
Correct answer: They are hoisted but not initialized (temporal dead zone)
Class declarations are hoisted but remain in the temporal dead zone until the declaration is reached, so they cannot be used before they appear.
What does the `hasOwnProperty()` method check?