Note_Tech

All technological notes.


Project maintained by simonangel-fong Hosted on GitHub Pages — Theme by mattgraham

JavaScript - Class

Back


Class

Keyword Description
extends Extends a class (inherit)
static Defines a static method for a class
super Refers to the parent class

Object Methods

console.log("\n-------- Class --------\n");

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

const myCar = new Car("Ford", 2014);

for (let p in myCar) {
  console.log(p, myCar[p]);
}
// name Ford
// year 2014

console.log("age", myCar.age()); //age 9

Getters and Setters

console.log("\n-------- Class: getter and setter --------\n");

class Car {
  constructor(brand) {
    this.carname = brand;
  }
  get cnam() {
    return this.carname;
  }
  set cnam(x) {
    this.carname = x;
  }
}

const myCar = new Car("Ford");

console.log(myCar.carname); //Ford

console.log(myCar.cnam);

myCar.cnam = "BMW"; //Ford
console.log(myCar.cnam); //BMW

Static class methods

console.log("\n-------- Class: static method --------\n");

class Car {
  constructor(brand) {
    this.carname = brand;
  }
  static hello() {
    return "Hello";
  }
}

const myCar = new Car("Ford");

// console.log(myCar.hello()); //raise an error.
console.log(Car.hello()); //Hello
console.log(Car.hello(myCar)); //Hello

Class Inheritance

console.log("\n-------- Class: inheritance --------\n");

class Car {
  constructor(brand) {
    this.carname = brand;
  }
  present() {
    return "I have a " + this.carname;
  }
}

class Model extends Car {
  constructor(brand, mod) {
    super(brand);
    this.model = mod;
  }
  show() {
    return this.present() + ", it is a " + this.model;
  }
}

let myCar = new Model("Ford", "Mustang");

console.log(myCar.present());
console.log(myCar.show());

TOP