Creating Properties
Let's discuss how to create properties and how they are different from getters and setters.
We'll cover the following...
Now, JavaScript supports C#-style properties. From the caller’s point of view, a property gives an illusion of a field but works as a method. Let’s revisit the Car
class we created in the previous lesson and introduce another method that returns a value and then turns it into a property.
Getters
Suppose we want to know how old a car is. The year of make is provided when an instance is created. We use the getAge()
method to find the age of the car, like so:
getAge() {
return new Date().getFullYear() - this.year;
}
The method subtracts the year of make from the current year. We invoke this method using the familiar method call syntax:
Press + to interact
'use strict';class Car {constructor(year) {this.year = year;this.miles = 0;}drive(distance) {this.miles += distance;}//START:GETgetAge() {return new Date().getFullYear() - this.year;}//END:GET}const car = new Car(2007);console.log(car.getAge());
That works, but getAge()
is a Java-style getter. ...
Access this course and 1400+ top-rated courses and projects.