javascripts class code example

Example 1: js class

class Car {
  constructor(brand, speed) {
    this.brand = brand
    this.speed = speed
  }
  speedUp() {
    this.speed += 5
    console.log(`The ${this.brand} is travelling at ${this.speed} mph`)
  }
  slowDown() {
    this.speed -= 5
    console.log(`The ${this.brand} is travelling at ${this.speed} mph`)

  }
}
const redCar = new Car('toyota', 0)
redCar.speedUp() // result: The toyota is travelling at 5 mph
redCar.slowDown() // result: The toyota is travelling at 0 mph

Example 2: javascript class

// unnamed
let Rectangle = class {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
};
console.log(Rectangle.name);
// output: "Rectangle"

// named
let Rectangle = class Rectangle5 {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
};
console.log(Rectangle.name);
// output: "Rectangle2"