Explore how JavaScript classes relate to prototypes, constructor functions, inheritance, and encapsulation in modern JavaScript. This easy quiz tests key concepts and features that help make your code clearer and more maintainable.
What is the primary purpose of the constructor method in a JavaScript class?
Explanation: The constructor method initializes properties for each new instance of a class. Static methods are defined using the 'static' keyword. Inheritance is handled by 'extends' and 'super', not the constructor itself. Methods are not stored privately in the constructor; they exist on the prototype.
Where are methods defined in a JavaScript class actually stored?
Explanation: Class methods are stored on the prototype, making them shared between instances and conserving memory. They are not placed inside each instance, nor directly in the constructor, and private fields are a separate feature.
Which syntax enables inheritance between two JavaScript classes?
Explanation: The 'extends' keyword allows one class to inherit properties and methods from another. 'implements' is not used in JavaScript for class inheritance; 'inherit' and 'derive' are not valid JavaScript syntax for inheritance.
How do static methods differ from regular methods in JavaScript classes?
Explanation: Static methods are called on the class itself and not on its instances. They do not automatically access instance properties and are not necessarily private. They are not executed just once per program.
What feature do private fields (e.g., #count) in JavaScript classes provide?
Explanation: Private fields using '#' provide true encapsulation, making those properties accessible only within the class. They do not affect prototype chain speed, do not enable method inheritance by themselves, and do not make properties globally accessible.
Why might using classes in JavaScript be unnecessary for simple objects?
Explanation: For small or simple objects, factory functions may be easier to use and read. Classes do support instance properties and private fields, and inheritance is not mandatory in every class.
What does it mean that JavaScript classes are 'syntactic sugar' over prototypes?
Explanation: JavaScript classes offer a familiar and concise syntax, but they work by leveraging the existing prototype system. They are closely tied to prototypes, can be used to create objects, and do not enforce strict encapsulation by default.
When is it particularly useful to use JavaScript classes?
Explanation: Classes are helpful for organizing complex objects, supporting method sharing, inheritance, and improving team readability. For simple utilities, classes can be unnecessary; avoiding code reuse or dynamic evaluation does not require the use of classes.