June 2018
Beginner
288 pages
6h 31m
English
JavaScript now supports C#-style properties. From the caller point of view, a property gives an illusion of a field but works as a method. Let’s revisit the Car class we created earlier and introduce another method that returns a value and then turn that into a property.
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:
| | const car = new Car(2007); |
| | |
| | console.log(car.getAge()); |
That works, but getAge() is a Java-style getter. ...
Read now
Unlock full access