Secure & Private (Zero Data Retention)
Free Access • No Sign-Up
ES6 Classes
Classes provide a cleaner syntax for creating objects and dealing with inheritance in JavaScript.
Try It Yourself
📋 Copy Modern JavaScript Class with Private Fields Snippet
// Modern Class with Private Fields & Static Factory
class UserAccount {
#passwordHash; // True private field enforced by engine
constructor(username, passwordHash) {
this.username = username;
this.#passwordHash = passwordHash;
}
static createDefault(username) {
return new UserAccount(username, "default_hash");
}
verify(hash) {
return this.#passwordHash === hash;
}
}
⚠️ 5 Fatal Traps & JavaScript Pitfalls
Trap #1: Losing this Context When Passing Methods as Callbacks
Passing button.addEventListener("click", user.verify) detaches the method from the instance, leaving this undefined. Bind the method or use an arrow function.
Trap #2: Accessing this Before super() in Subclasses
In a subclass constructor, referencing this before calling super() throws an immediate ReferenceError: Must call super constructor before accessing this.
Trap #3: JavaScript Classes Are NOT Hoisted
Unlike function declarations, classes are in the Temporal Dead Zone until execution reaches them. Instantiating a class before its declaration throws a ReferenceError.
Trap #4: Private Field Syntax (#field) Outside Class Error
Attempting to access user.#passwordHash outside the class declaration is a syntax error caught at parse-time.
Trap #5: Classes Are Syntactic Sugar Over Prototypes
Underneath the hood, JavaScript classes still use prototype chains. Methods are attached to Class.prototype, not copied onto each instance.
💬 Frequently Asked Questions
How do private fields (#) work in modern JavaScript classes?
Prefixing a field name with # enforces hard encapsulation at the engine level. Private fields cannot be accessed, modified, or detected from outside the class body.
What is the super keyword used for in classes?
super() calls the parent class constructor, and super.method() invokes parent prototype methods in subclass overrides.
What are static methods and fields on classes?
Static members belong to the class constructor function itself rather than individual instances, accessed via ClassName.method().
What are getters and setters in classes?
get prop() and set prop(val) define methods that are accessed with property syntax, enabling validation and computed attributes.
How does inheritance work with class extends?
class Sub extends Super sets up the prototype chain so Sub.prototype inherits from Super.prototype, and Sub inherits static properties from Super.