Coding for All
Lesson 6: A Team of Objects
A Team of Objects Combine classes with arrays and loops.
1class Player {
2 constructor(name, score) {
3 this.name = name;
4 this.score = score;
5 }
6
7 cheer() {
8 console.log(`Go ${this.name}! Score: ${this.score}`);
9 }
10}
11
12const ada = new Player("Ada", 100);
13const grace = new Player("Grace", 120);
14const players = [ada, grace];
15for (const player of players) {
16 player.cheer();
17}
Terminal
$ node main.js
Go Ada! Score: 100
Go Grace! Score: 120
Every line, explained
class Player {
class Dog { ... } defines a class: a blueprint describing what every Dog has and can do. A blueprint on its own does nothing; it is a plan, waiting to be built from. This blueprint is for game players.
constructor(name, score) {
constructor is a special method that runs AUTOMATICALLY when new Dog(...) is built. It is where you fill in the object's starting values. (Note there is no function keyword on methods inside a class.)
this.name = name;
This player's name.
this.score = score;
This player's score.
}
This } closes the constructor.
cheer() {
Something every Player can do.
console.log(`Go ${this.name}! Score: ${this.score}`);
Uses both of this player's stored values.
}
This } closes the method.
}
This } closes the class.
const ada = new Player("Ada", 100);
One player...
const grace = new Player("Grace", 120);
...and another.
const players = [ada, grace];
Objects can go in an array, just like numbers or strings!
for (const player of players) {
And for...of can visit each object in turn: everything from Intro to JavaScript works with your own classes.
player.cheer();
Each player cheers with their own name and score. Classes, arrays and loops together: that is real object-oriented JavaScript!
}
This } closes the for loop.