HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

JavaScript Classes Intro

JavaScript Classes are templates for JavaScript Objects. Introduced in ES6 (2015), they provide a much cleaner and more structured way to create objects and deal with inheritance than the older prototype-based approach.


Class Syntax

Use the keyword class to create a class. Always add a method named constructor():

class Car {
  constructor(name, year) {
    this.name = name;
    this.year = year;
  }
}

The constructor method is special—it is executed automatically when a new object is created.


Creating an Object

Use the new keyword to create an object from the class template.

const myCar1 = new Car("Ford", 2014);
const myCar2 = new Car("Audi", 2019);

Class Methods

You can add methods to your classes just like you would with objects. Methods are shared across all instances of the class.

class Car {
  constructor(name, year) {
    this.name = name;
    this.year = year;
  }
  age() {
    let date = new Date();
    return date.getFullYear() - this.year;
  }
}

let myCar = new Car("Ford", 2014);
console.log("My car is " + myCar.age() + " years old.");
Strict Mode: JavaScript classes are always executed in Strict Mode. If you don't follow strict rules, the code will throw an error even without the "use strict"; directive.

Key Points to Remember

  • Classes are not objects, they are blueprints for objects
  • The constructor() method is where you initialize properties
  • Use the new keyword to create an instance
  • Classes are not hoisted (unlike functions)—you must declare it before using it
  • Classes allow for Encapsulation, keeping data and logic together
  • Methods can take parameters just like regular functions