Coding for All
Lesson 2: The constructor
The constructor Give each object its own starting values.
1class Dog {
2 constructor(name) {
3 this.name = name;
4 }
5}
6
7const rex = new Dog("Rex");
8console.log(rex.name);
Terminal
$ node main.js
Rex
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 one takes a name, a value the builder must hand in.
this.name = name;
Stores the name ON the object itself: this.name is "this dog's name box". Plain name is just the value passed in; this.name is where it gets kept.
}
This } closes the constructor.
}
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. The "Rex" goes straight to the constructor, so the object is born with its name already set.
console.log(rex.name);
console.log(...) works exactly as in Intro to JavaScript. The dot reads a value back out: rex.name is whatever was stored on rex.