Objects That Remember
Change an object's values; it remembers!
1class Dog {
2 constructor(name, age) {
3 this.name = name;
4 this.age = age;
5 }
6
7 birthday() {
8 this.age = this.age + 1;
9 console.log(`${this.name} is now ${this.age}!`);
10 }
11}
12
13const rex = new Dog("Rex", 3);
14rex.birthday();
15rex.birthday();
$ node main.js
Rex is now 4!
Rex is now 5!
Every line, explained
class Dog {- 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.
constructor(name, age) {- 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.) Two values this time.
this.name = name;- This dog's name box.
this.age = age;- This dog's age box.
}- This } closes the constructor.
birthday() {- A method that CHANGES the object.
this.age = this.age + 1;- Adds 1 to this dog's stored age. The object keeps the new value; objects remember!
console.log(`${this.name} is now ${this.age}!`);- console.log(...) works exactly as in Intro to JavaScript.
}- This } closes the method.
}- This } closes the class.
const rex = new Dog("Rex", 3);- rex is born aged 3.
rex.birthday();- First birthday: 3 becomes 4.
rex.birthday();- Second birthday: rex REMEMBERED being 4, so now he is 5. Each object carries its own memory around.