Would you like to clone this notebook?

When you clone a notebook you are able to make changes without affecting the original notebook.

Cancel

WCTD - Level 2, Session 2 (Classes & Objects)

node v15.14.0
version: 1.0.0
endpointsharetweet
{ class Car { constructor(year, make, model) { this.year = year; this.make = make; this.model = model; this.fuel = 0; this.mileage = 0; } } // and creating an instance is via `new` const myNewCar = new Car("2021", "Toyota", "Corolla"); console.log(myNewCar.mileage); // 0 }
class Car { constructor(year, make, model) { this.year = year; this.make = make; this.model = model; this.fuel = 0; this.mileage = 0; } drive(miles) { this.mileage += miles; } addFuel(fuel) { this.fuel += fuel; } } const myNewCar = new Car("2021", "Toyota", "Corolla"); myNewCar.drive(500); myNewCar.addFuel(11); console.log(myNewCar.mileage, myNewCar.fuel); // 500, 11
class GasStation { constructor(fuelInGallons) { this.fuel = fuelInGallons; } fillCar({car, withGallons}) { if (this.fuel - withGallons > 0) { car.addFuel(withGallons); this.fuel -= withGallons; } else { throw new Error("Gas station would be out of gas!"); } } } const aGasStation = new GasStation(1000); // start with 1000 gallons aGasStation.fillCar({car: myNewCar, withGallons: 11}); console.log(aGasStation.fuel, myNewCar.fuel); // 989, 22
Loading…

no comments

    sign in to comment