class Car {
constructor(make, model) {
this._make = make
this._model = model
this._miles = 30
}
get make() {
return this._make
}
get model() {
return this._model
}
get miles() {
return this._miles
}
set model(newModel) {
this._model = newModel
}
drive(newMiles) {
console.log(`driving ${newMiles} miles`)
this._miles = this._miles + newMiles
}
}
const myTesla = new Car("Telsa", "Model 3")
console.log(myTesla.make)
console.log(myTesla.miles)
// call instance.addMilage() method
// to add additional miles
myTesla.drive(15)
myTesla.drive(7)
console.log(myTesla.miles)
Here’s a summary of the code above:
We’ve specified a new property miles
and set it to 30 for each new Car
instance
Next, we added a getter method for miles, that simply returns the value stored in the miles
property
Then, we created a “regular” method drive()
that accepts a parameter (newMiles) and updates our miles property with a new value