Writing Classes Lesson

A class is a blueprint for creating objects that share the same structure and behavior. The class defines what data each object should store and what methods each object can use. This keeps related code organized in one place.

Code Runner Challenge

Writing Classes Lesson

View IPYNB Source
%%js

// CODE_RUNNER: Writing Classes Lesson

class PlayerProfile {
  constructor(name, level) {
    this.name = name;
    this.level = level;
  }

  describe() {
    console.log(this.name + " is level " + this.level);
  }
}

const profile = new PlayerProfile("Nova", 4);
profile.describe();
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

Classes are useful when a program needs many similar objects. Instead of copying the same properties and functions again and again, the program creates new instances from the class.

The constructor runs when a new object is created. It receives the starting data and assigns that data to the object with this, so each object can keep its own values.