JavaScript ES6 Classes

Classes are a template for creating objects. They encapsulate data with code to work on that data.

ES5 Class Declaration #

var Person = function () {

}

ES6 Class Declaration #

class Person {

}

class Person {
constructor(name = 'Guest', surname = 'Guest', birthday) {
this.name = name;
this.surname = surname;
this.birthday = birthday;
}
greeting(text){
return `${text} I'm ${this.name}`;
}
}
const person1 = new Person("Yasin", "Genc", 1993);
console.log(person1);
console.log(person1.greeting("Good Morning"));

Guest is our default value.

Here we're creating Student class from Person class. super calls the parent constructor.

class Student extends Person {
constructor(name, surname, birthday, studentNumber) {
super(name, surname, birthday);
this.studentNumber = studentNumber;
}
greeting(text) {
let str = super.greeting(text);
str += `My number is ${this.studentNumber}`;
return str;
}
}
const student1 = new Student("Linda", "Schiffer", 2008, "123456");
console.log(student1);
console.log(student1.greeting("Hello"));
Previous Post

Differences Between Const, Var and Let

My notes about const, var and let. Not a guide. Just notes.

Read article