JavaScript Prototypes and Classes 2 — Questions and Answers
Question 1: What does `Object.getPrototypeOf(obj)` return?
- The prototype of obj (Correct answer)
- The constructor of obj
- A copy of obj
- The keys of obj
Correct answer: The prototype of obj
`Object.getPrototypeOf(obj)` returns the prototype (i.e., the value of the internal `[[Prototype]]`) of the specified object.
Question 2: Which keyword is used to call the parent class constructor inside a subclass?
- this()
- parent()
- super() (Correct answer)
- base()
Correct answer: super()
`super()` must be called in a subclass constructor before using `this`, invoking the parent class constructor.
Question 3: What is the result of `typeof class Foo {}`?
- 'object'
- 'class'
- 'function' (Correct answer)
- 'undefined'
Correct answer: 'function'
Classes in JavaScript are syntactic sugar over functions, so `typeof` returns `'function'`.
Question 4: How do you define a static method in a JavaScript class?
- Using the `global` keyword before the method
- Using the `static` keyword before the method (Correct answer)
- Placing it outside the class body
- Assigning it to `this.prototype`
Correct answer: Using the `static` keyword before the method
The `static` keyword defines a method that belongs to the class itself, not to instances.
Question 5: What happens when you access a property that doesn't exist on an object or its prototype chain?
- An error is thrown
- It returns null
- It returns undefined (Correct answer)
- It returns false
Correct answer: It returns undefined
JavaScript traverses the prototype chain and returns `undefined` if the property isn't found anywhere in the chain.
Question 6: Which method creates an object with a specified prototype object?
- Object.assign()
- Object.create() (Correct answer)
- Object.defineProperty()
- Object.freeze()
Correct answer: Object.create()
`Object.create(proto)` creates a new object whose `[[Prototype]]` is set to `proto`.
Question 7: What is a 'mixin' in the context of JavaScript classes?
- A built-in method for merging objects
- A pattern to add methods from multiple sources to a class (Correct answer)
- A special class that extends two parents
- A private field decorator
Correct answer: A pattern to add methods from multiple sources to a class
A mixin is a design pattern where methods from one or more objects are copied into a class to achieve multiple-inheritance-like behavior.
What does `Object.getPrototypeOf(obj)` return?