JavaScript, lesson 10
As programs grow, loose variables become hard to follow. Grouping related data, and the code that works on it, into one unit makes a program read like a description of the problem. In JavaScript you have two main tools: object literals for simple records and classes for things with behaviour and rules.
{ name, age } is shorthand for { name: name, age: age }. The spread ...pet copies all of
pet's properties into a new object, which is a clean way to make a changed copy without
touching the original.
Objects can hold functions too, called methods. Inside a method, this refers to the
object the method was called on.
When you need many objects of the same shape with the same behaviour, write a . It is a blueprint; builds an object (an ) from it:
2 exercises to try what you just read.
newconstructor runs once when new Counter(...) is called. It sets up the fields.steps.increment().get value()) is a method you read like a property, with no parentheses.# are private. Code outside the class cannot read or change
steps.#count; it is a syntax error. Private fields let a class protect its rules, for
example that a balance never goes negative.toString() is used automatically when the object is placed in a template literal.A static method or field belongs to the class itself, not to instances. It is a good place
for helpers that create instances from other data:
class Dog extends Animal creates a class that starts with everything Animal has and can add
or replace methods. Its constructor must call super(...) before using this. You already saw
this with custom errors. Use inheritance sparingly: small classes that contain other objects
are usually easier to change than deep family trees of classes.
Use object literals for plain data, such as one line of parsed input. Use a class when the data has rules to protect or several operations that belong together.
Write a class Account with:
0 and is stored in a
private field #balance;deposit(amount): adds the amount;withdraw(amount): subtracts it, but if the amount is larger than the balance it throws an
Error with message insufficient funds and leaves the balance unchanged;balance that returns the current balance.The program below your class is already written. It reads commands such as deposit 50,
withdraw 20 and show, and prints Ana: 30 for show or error: insufficient funds
when a withdrawal fails. The first line of input is the owner's name.
Sample input:
Sample output:
Write a class Duration that stores a length of time in whole seconds:
constructor(seconds) stores the total;static parse(text) builds a Duration from text like 1:05:30 (hours, minutes,
seconds) or 4:12 (minutes, seconds);plus(other) returns a new Duration that is the sum of both;toString() returns H:MM:SS, with minutes and seconds always two digits.Each input line is one lap time. Print every lap as Lap N: H:MM:SS, then the total as
Total: H:MM:SS.
Sample input:
Sample output:
const name = "Rex";
const age = 4;
const pet = { name, age, species: "dog" }; // { name: "Rex", age: 4, species: "dog" }
const { species, age: years } = pet; // destructuring, with a rename
const older = { ...pet, age: 5 }; // copy with one property changed
console.log(species, years, older.age); // dog 4 5class Counter {
#count = 0; // a private field
constructor(label) {
this.label = label; // a public field
}
increment(by = 1) {
this.#count += by;
return this; // returning this allows chaining
}
get value() { // a getter: read like a property
return this.#count;
}
toString() {
return `${this.label}: ${this.#count}`;
}
}
const steps = new Counter("steps");
steps.increment().increment(5);
console.log(steps.value); // 6
console.log(`${steps}`); // steps: 6class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
static parse(text) { // Point.parse("3,4")
const [x, y] = text.split(",").map(Number);
return new Point(x, y);
}
distanceTo(other) {
return Math.hypot(this.x - other.x, this.y - other.y);
}
}
console.log(Point.parse("0,0").distanceTo(new Point(3, 4))); // 5Ana
deposit 50
withdraw 20
show
withdraw 100
showAna: 30
error: insufficient funds
Ana: 304:12
1:05:30Lap 1: 0:04:12
Lap 2: 1:05:30
Total: 1:09:42