Learn JavaScript · lesson 54 of 60 · about 9 minutes
Methods, Getters and static
Give a class behaviour, properties that work themselves out, and helpers that belong to the class.
What you'll learn
- Write methods that use this
- Add a getter for a computed property
- Write a static method on the class
Fixing bugs
Bugs need fixing, so Bug gets some behaviour. takeHit(damage) takes hp away, never below 0; the getter fixed says whether a bug has no hp left; and the getter status sums it up, as Typo: 1 of 3 hp left or Typo is fixed. A visitor can report a bug too, as text like Missing semicolon:2, and Bug.fromReport() turns that into a Bug, or gives back null when the text isn't a report. Then Sam makes the quickFixes on the first bug straight away.
Methods
A method is a function written inside the class. Every object gets it, and inside it this is the object the method was called on. Methods can read and change that object's properties.
A bank account
class Account {
constructor(owner) {
this.owner = owner;
this.balance = 0;
}
deposit(amount) {
this.balance += amount;
}
describe() {
return `${this.owner} has ${this.balance}`;
}
}
const acc = new Account("Ada");
acc.deposit(50);
acc.deposit(25);
console.log(acc.describe());Output
Ada has 75Getters and static
A getter, written get name() { ... }, looks like a property from outside but works its value out each time: circle.area, with no brackets.
A static method belongs to the class itself, not to each object. You call it on the class name: Temperature.fromFahrenheit(212).
A getter and a static method
class Temperature {
constructor(celsius) {
this.celsius = celsius;
}
get fahrenheit() {
return this.celsius * 9 / 5 + 32;
}
static fromFahrenheit(f) {
return new Temperature((f - 32) * 5 / 9);
}
}
const t = new Temperature(100);
console.log(t.fahrenheit);
console.log(Temperature.fromFahrenheit(32).celsius);Output
212
0Why fromReport is static
fromReport makes a new bug from text, so there's no bug yet to call it on: it belongs to the class, Bug.fromReport(bugReport). A report needs a name and a whole number of hp from 1 up, so "Missing semicolon" with no hp, or "Typo:0", gives null, and the page says it's not a bug report.
Tip
Inside a method, always write this.balance, not just balance. Without this, JavaScript looks for a variable called balance and doesn't find one.
Now try it yourself
This lesson is free in Codiqo, with 8 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.