Two Dogs
Build two objects from one blueprint.
1class Dog {
2 constructor(name) {
3 this.name = name;
4 }
5}
6
7const rex = new Dog("Rex");
8const bella = new Dog("Bella");
9console.log(rex.name);
10console.log(bella.name);
$ node main.js
Rex
Bella
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;- Each new dog gets its OWN name box.
}- This } closes the constructor.
}- This } closes the class.
const rex = new Dog("Rex");- One blueprint...
const bella = new Dog("Bella");- ...as many objects as you like. Think of one house plan and a whole street of houses. bella's name box is completely separate from rex's.
console.log(rex.name);- console.log(...) works exactly as in Intro to JavaScript.
console.log(bella.name);- console.log(...) works exactly as in Intro to JavaScript. Two objects, two different names.