Class Declaration
Class Declaration
Section titled “Class Declaration”Introduction
Section titled “Introduction”A class declaration is the primary way to define classes in JavaScript. Classes are functions under the hood — they’re syntactic sugar over constructor functions and prototypes.
Basic Syntax
Section titled “Basic Syntax”class User { constructor(name, email) { this.name = name; this.email = email; }
greet() { return `Hello, I'm ${this.name}`; }}
const user = new User('Alice', 'alice@email.com');console.log(user.greet()); // "Hello, I'm Alice"console.log(typeof User); // 'function' — classes are functions!Class vs Function Constructor
Section titled “Class vs Function Constructor”// Class syntaxclass Person { constructor(name) { this.name = name; } greet() { return `Hi, ${this.name}`; }}
// Equivalent function constructorfunction Person(name) { this.name = name;}Person.prototype.greet = function() { return `Hi, ${this.name}`;};
// They work the same way:const alice = new Person('Alice');console.log(alice.greet()); // "Hi, Alice"Class Expressions
Section titled “Class Expressions”Classes can be named or anonymous:
// Anonymous class expressionconst User = class { constructor(name) { this.name = name; }};
// Named class expressionconst Admin = class AdminClass { constructor(name) { this.name = name; } getClassName() { return AdminClass.name; }};
// First-class — can be passed aroundfunction createClass(className) { return class { constructor(name) { this.name = name; } greet() { return `Hi from ${className}`; } };}const MyClass = createClass('Custom');Key Characteristics
Section titled “Key Characteristics”- Classes are not hoisted (unlike function declarations)
- Code inside a class is always strict mode
- Methods are non-enumerable on the prototype
- Cannot call a class without
new(throws TypeError)
// ❌ Not hoistedconst obj = new MyClass(); // ReferenceErrorclass MyClass {}
// ❌ Must use newUser(); // TypeError: Class constructor User cannot be invoked without 'new'typeof and instanceof
Section titled “typeof and instanceof”class Rectangle { constructor(w, h) { this.w = w; this.h = h; } area() { return this.w * this.h; }}
console.log(typeof Rectangle); // 'function'console.log(Rectangle.prototype.area); // [Function: area]console.log(Rectangle.prototype.constructor === Rectangle); // true
const rect = new Rectangle(3, 4);console.log(rect instanceof Rectangle); // trueconsole.log(rect instanceof Object); // trueSummary
Section titled “Summary”classsyntax is syntactic sugar over prototypes- Classes are not hoisted — declare before use
- Class code is always in strict mode
- Methods are added to the prototype
- Must use
newto instantiate