Notes

[ES2015] Classes in JavaScript

Edit on GitHub

JavaScript
2 minutes

ES2015 / ES6 Classes in JavaScript

Classes in JS don’t give JS an OO nature, JS remains Prototypal. Classes introduced in ES6 are mainly syntax sugar.

 1"use strict";
 2
 3// CLASS
 4class User{
 5  // Constructor
 6  // takes any values/attr you want to set
 7  constructor(username, email, password) {
 8    this.username = username // Whatever username we passed in is now this Class's (instance) username
 9    this.email = email
10    this.password = password
11  }
12
13  static countUsers () {
14    console.info('There are 50 users')
15  }
16
17  // Methods
18  register() {
19    console.log(`${this.username} is now registered`)
20  }
21}
22
23// Instantiate the class
24let Bob = new User('bob', 'bob@bobby.com', '123supersecretpass')
25
26// Call a method 
27Bob.register() // bob is now registered
28
29// INHERITANCE
30class Memeber extends User {
31  constructor(username, email, password, memberPackage) {
32    super(username, email, password)
33    this.package = memberPackage
34  }
35
36  getPackage() {
37    console.info(`${this.username} is subscribed to the ${this.package} package`)
38  }
39
40}
41let mike = new Member('mike', 'mike@email.com', 'pass123', 'Standard')
42
43mike.register() // mike is now registereds
44mike.getPackage() // mike is subscribed to the Standard package

Constructors

Constructors are methods that’ll run when your class is instantiated. They can take parameters. You can then set these params (passed in values) and assign them to class properties.

Methods

Methods are functions that belong to a class. You can call them on an instance of a class, like so:

1Bob.register() // bob is now registereds

You can also have static methods. Whatever. Static methods can be called without having to instantiate a class, like this:

1User.countUsers() // There are 50 users

Inhertitence

You can extend existing classes to create new classes. super constructor calls (functions etc.) on theconstructor in the parent class. super needs to be called before you can use the this keyword.

1class Member extends User {}

Classes vs Functions?

You should create a class whenever you have code that needs to be self-aware or keep something in memory. Whatever that means.

Related