JavaScript Classes: constructor, Methods, extends
A class is a template for creating objects that share the same shape and behavior. new Account("Ava") creates an instance: a new object with its own data, and access to the methods defined in the class. Classes arrived in ES2015 as cleaner syntax over JavaScript's older prototype system, and they are standard in modern code.
constructor and this
The constructor method runs when you call new. Inside it, this is the new object, and assignments like this.owner = owner create its properties. Methods written in the class body, such as deposit, are shared by all instances. Returning this from a method enables chaining, as in new Account("Ava").deposit(50).deposit(25).
Private fields, getters and static members
#balance = 0declares a private field. Only code inside the class can read or write it;acc.#balanceoutside the class is a syntax error. That protects the balance from being changed without going throughdeposit, which validates the amount.get balance()defines a getter: callers readacc.balancelike a property, but a method runs behind the scenes.static count = 0belongs to the class itself rather than to instances, so it is read asAccount.count. Here it counts how many accounts were created.
Expected output
Ava 75 220 true 2 function ["owner", "rate"]
Inheritance with extends
class Savings extends Account creates a subclass that inherits everything from Account. A subclass constructor must call super(...) before it uses this; that runs the parent constructor. Methods can call inherited methods with this.deposit(...), or the parent's version of an overridden method with super.deposit(...). instanceof checks the chain: a Savings object is also an Account.
The last line of the output shows two facts about classes. typeof Account is "function", because a class is a special kind of function under the hood. And Object.keys(s) lists only the public own properties, owner and rate; the private field is invisible.
When to use classes
Classes suit things with both data and behavior that you create many of, such as accounts, UI components or game entities. For simple data, plain objects and functions are often enough. Unlike function declarations, classes are not hoisted: define them before you use them.
Common mistakes
- Forgetting
new, which throwsTypeError: Class constructor Account cannot be invoked without 'new'. - Using
thisin a subclass constructor before callingsuper(). - Passing a method as a callback, as in
setTimeout(acc.deposit, 10), and losingthis. Wrap it in an arrow function.
Summary
class+constructordefine how instances are built;newcreates them.- Methods are shared;
#privatefields hide data;getdefines computed properties;staticbelongs to the class. extendsandsuper()create subclasses.
Quiz: Classes