Lesson 1 · Unit 07
Classes
Blueprints for objects: constructor, methods, this
What you practise
class,constructor, methods,this, getters,static, private#fields, many instances of one class
Try a question from this lesson
Pick one
This function builds dog objects. It is called twice, and then one dog is renamed. What prints?
function makeDog(name) {
return { name: name, sound: "Woof" };
}
const a = makeDog("Rex");
const b = makeDog("Fido");
a.name = "Max";
console.log(a.name, b.name);Correct answer
Max Fido
Why
Every call returns a brand-new object, so a and b are two separate dogs and renaming one leaves the other alone. Building many objects of the same shape is so common that JavaScript has a special form for it: the class.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
A class is a blueprint
new Dog("Rex") makes a fresh object, called an instance, and runs the constructor to set it up.
Inside the class, this means "the object being built or used". this.name = name stores the name on it.
A function written inside a class is a method. Every instance can call it.
class Dog {
constructor(name) {
this.name = name;
}
speak() {
return this.name + " says woof";
}
}
const rex = new Dog("Rex");
console.log(rex.speak()); // Rex says woofConcept
Getters and static
A getter is a method you read like a property, with no brackets. It is worked out fresh every time you read it. Write get in front of it.
A static method belongs to the class itself, not to its instances. Call it on the class name. It is often used for another way to build an instance.
class Temp {
constructor(c) {
this.c = c;
}
get f() {
return this.c * 2 + 30; // roughly
}
static freezing() {
return new Temp(0);
}
}
const t = Temp.freezing();
console.log(t.f); // 30 (no brackets)Concept
Private fields
A field whose name starts with # is private. Only code inside the class can read or change it. Outside the class, writing acct.#balance is an error before the program even starts.
Now the class decides what can happen to its data. Here the only way to change the balance is a deposit of more than zero.
class Account {
#balance = 0;
deposit(n) {
if (n <= 0) throw new Error("bad");
this.#balance += n;
}
get balance() {
return this.#balance;
}
}
const acct = new Account();
acct.deposit(50);
console.log(acct.balance); // 509 more exercises in the app
- 2× type the answer
- 1× fill the blanks
- 3× multiple choice
- 1× true or false
- 1× order the lines
- 1× match the pairs
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.