Classes
What is a class?
Section titled “What is a class?”A class is a blueprint for creating objects that share the same properties and methods.
Under the hood, JavaScript classes are syntactic sugar over the prototype-based inheritance system.
➡ They make code more readable and familiar to object-oriented programmers.
Declaring a class
Section titled “Declaring a class”A class can contain:
- a constructor → a special function executed when creating the object,
- methods → functions defined within the class.
class Person { constructor(name, age) { this.name = name; this.age = age; }
introduce() { console.log(`My name is ${this.name} and I am ${this.age} years old.`); }}
let alice = new Person("Alice", 25);alice.introduce(); // My name is Alice and I am 25 years old.
Inheritance
Section titled “Inheritance”Using extends
, a class can inherit from another.
Use super()
to call the parent class’s constructor.
class Animal { constructor(name) { this.name = name; }
speak() { console.log(`${this.name} makes a noise.`); }}
class Dog extends Animal { constructor(name, breed) { super(name); // calls Animal constructor this.breed = breed; }
speak() { console.log(`${this.name} barks.`); }}
let rex = new Dog("Rex", "German Shepherd");rex.speak(); // Rex barks.
Static methods
Section titled “Static methods”A method can be declared static
→ it is called directly on the class, not on an instance.
class Maths { static add(a, b) { return a + b; }}
console.log(Maths.add(2, 3)); // 5
Best practices
Section titled “Best practices”- Use classes to model entities (e.g.,
User
,Product
). - Employ
extends
+super
to reuse code and facilitate inheritance. - Prefer static methods when the action does not depend on a specific instance.
- Keep in mind that classes are syntactic sugar → JavaScript still uses the prototype mechanism under the hood.