June 2018
Beginner
288 pages
6h 31m
English
Methods are an integral part of classes. They exhibit behavior and are often used to perform some action, and possibly to effect state change.
To define a method, place the function body within the {} of the class definition—but without the function keyword. Let’s rewrite the Car class, this time adding another field and a method.
| | class Car { |
| | constructor(year) { |
| | this.year = year; |
| | this.miles = 0; |
| | } |
| | |
| | drive(distance) { |
| | this.miles += distance; |
| | } |
| | } |
In the constructor we initialized this.year to the value received in the year parameter and initialized this.miles to a value of 0. In the drive() method we increase the this.miles value by the value received in the distance parameter. ...
Read now
Unlock full access