Constructor Functions to Classes

What are JavaScript ES6 Classes?

In JavaScript, classes are a blueprint for creating objects with shared properties and methods. Introduced in ES6, they provide a cleaner and more structured way to implement object-oriented programming compared to traditional constructor functions.

The constructor is a special method within a class that is automatically called when a new instance of the class is created. It is used to initialize the object's properties and set up any necessary logic.

Here's an example from index.js of a class used instead of a constructor function:

            
// Class Constructor Function
class Gamer {
    constructor(name, score) {
        this.name = name
        this.score = score
    }
    
    incrementScore() {
        this.score++  
    }
}

const dave = new Gamer('Dave', 0)
const sarah = new Gamer('Sarah', 0)
dave.incrementScore()
console.log(dave)
console.log(sarah)
            
        

In this example, we define a class named Gamer with a constructor that initializes the name and score properties. The class also includes a method called incrementScore that increases the player's score by one. We then create two instances of the Gamer class, dave and sarah, and call the incrementScore method on dave.

View Challenge

References:

Open the console to see the output