Line At A Time
Lesson 1: What Is a Class?
What Is a Class? Write a blueprint and build an object from it.
1class Dog {
2 bark() {
3 console.log("Woof!");
4 }
5}
6
7const rex = new Dog();
8rex.bark();
Terminal
$ node main.js
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. Class names start with a Capital letter by convention.
bark() {
A method: something every Dog can do. Inside a class you write just the name and brackets, no function keyword.
console.log("Woof!");
console.log(...) works exactly as in Intro to JavaScript.
}
This } closes the method.
}
This } closes the class.
const rex = new Dog();
new Dog(...) builds a real object from the blueprint. The blueprint is the plan; the object is an actual dog. rex now holds one actual dog.
rex.bark();
The dot asks the object to do one of its tricks: rex.bark() means "rex, bark!".