ES6 Classes in JavaScript tutorial

Image for post
Image for post
class Test{

}
console.log(typeof(Test))

Class declaration

class Person{
constructor(firstName,lastName){
this.firstName = firstName;
this.lastName = lastName;
}

Class expression

let Person = class Person2{ constructor(firstName,lastName){ this.firstName = firstName;this.lastName = lastName;}}
let Person = class {
constructor(firstName,lastName){
this.firstName = firstName;
this.lastName = lastName;
}
sayHello(){
console.log('hello ' + this.firstName + ' ' + this.lastName)
}
}
var Alex = new Person('Alex','test')
console.log(Alex.sayHello())
console.log(Person.name)

Constructor

Defining methods

class Person {constructor(firstName) {
this._firstName = firstName

}

get name() {
return 'my name is: ' + this._firstName
}
set name(newFirstName) {
this._firstName = newFirstName

}
}
let myName = new Person('Alex')
console.log(myName.name)
myName.name = 'Jack'
console.log(myName._firstName)

Static methods

class Person {constructor(firstName) {
this._firstName = firstName

}

get name() {
return 'my name is: ' + this._firstName
}
set name(newFirstName) {
this._firstName = newFirstName

}

static testStaticMethod(){
return 'this is a static method!'
}
}
let myName = new Person('Alex')
console.log(Person.testStaticMethod())
console.log(myName.testStaticMethod())

Extends

class Animal{
constructor(species,name){
this._species = species;
this.name = name;
}

saySpecies(){
console.log(this._species)
}

sayName(){
console.log(this_name)
}
}
class Snake extends Animal{
constructor(species){
super(species);
}

saySpecies(){
console.log(' i am snake and i am part of the ' + this._species + ' species')
}
}
let rattleSnake = new Snake('Rattlesnake')
rattleSnake.saySpecies()

Hoisting

var s = new Snake();class Snake {}

Software Developer in the UK. With a keen passion for React Native.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store