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:
That works, but getAge() is a Java-style getter. C# developers write properties instead of getter methods, and JavaScript now provides the same capability. A property may ...