Instantiation and Objects Lesson

Instantiation means creating an object from a class. The class is the blueprint, and the object is the actual thing the program can use. Each object made from the class is called an instance.

Code Runner Challenge

Instantiation and Objects Lesson

View IPYNB Source
%%js

// CODE_RUNNER: Instantiation and Objects Lesson

class Enemy {
  constructor(name, x) {
    this.name = name;
    this.x = x;
  }

  move() {
    this.x = this.x + 3;
  }
}

const firstEnemy = new Enemy("Scout", 20);
const secondEnemy = new Enemy("Guard", 80);
firstEnemy.move();

console.log(firstEnemy.x);
console.log(secondEnemy.x);
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

Instances can share the same methods while storing different data. This makes classes powerful because one definition can create many independent objects.

Both objects come from the same Enemy class, but they store different names and positions. Moving one enemy does not automatically move the other.