javascript what is a 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 create class

class Person {
 constructor(name, age) {
   this.name = name;
   this.age = age;
 }
  present = () => { //or present(){
  	console.log(`Hi! i'm ${this.name} and i'm ${this.age} years old`) 
  }
}
let me = new Person("tsuy", 15);
me.present();
// -> Hi! i'm tsuy and i'm 15 years old.

Example 3: javascript classes

class Rectangle {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
  // Getter
  get area() {
    return this.calcArea();
  }
  // Method
  calcArea() {
    return this.height * this.width;
  }
}

const square = new Rectangle(10, 10);

console.log(square.area); // 100

Example 4: variables in js class

constructor(){
    this.foo = bar
}

Tags:

Java Example