All technological notes.
JavaScript Classes are templates for JavaScript Objects.
Define a class
class to create a class.constructor()Using a Class
Hoisting
| Keyword | Description |
|---|---|
extends |
Extends a class (inherit) |
static |
Defines a static method for a class |
super |
Refers to the parent class |
constructor
Class methods are created with the same syntax as object methods.
Example
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
Use the get and set keywords, to add getters and setters in the class,
getter
setter
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 method on an object, only on an object class.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
Inheritance is useful for code reusability: reuse properties and methods of an existing class when you create a new class.
To create a class inheritance, use the extends keyword.
A class created with a class inheritance inherits all the methods from another class.
super
super()
constructor methodconsole.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());