Defining a Method

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.

A method may take zero, one, or more parameters, including default and rest parameters. Methods may access and modify any fields of the class and may perform actions. They may also access any variable in their scope and invoke functions in their scope, including other methods of the instance. However, unlike in languages like Java and C#, we have to use this. to refer to other methods of the instance. For example, use this.turn() to invoke a hypothetical turn() method of the instance. Without the this., JavaScript will look for a turn() function in the lexical scope of the class definition and not an instance method. If such a method does not exist in the lexical scope, then we’ll get a runtime error.

JavaScript restricts the characters that can make a field or a method name. However, it provides an easy way to work around its own restriction, as we’ll see next.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset