Coding for All
Lesson 4: Methods That Use this
Methods That Use this Let a method use the object's own values.
1class Dog {
2 constructor(name) {
3 this.name = name;
4 }
5
6 bark() {
7 console.log(`${this.name} says woof!`);
8 }
9}
10
11const rex = new Dog("Rex");
12rex.bark();
Terminal
$ node main.js
Rex says woof!
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) {
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;
Stores this dog's name.
}
This } closes the constructor.
bark() {
A second method. Because methods can use this, they can look at THIS dog's stored values.
console.log(`${this.name} says woof!`);
A template literal using this.name, so every dog barks its own name. When rex barks, this is rex.
}
This } closes the method.
}
This } closes the class.
const rex = new Dog("Rex");
new Dog(...) builds a real object from the blueprint. The blueprint is the plan; the object is an actual dog.
rex.bark();
rex barks, and the method prints rex's own name.