Classes and inheritance

Class definition in ES6 is similar to other object oriented languages like Java or C#. The keyword for defining the classes is class. The class can have fields, constructors, and class methods. The following sample code shows the ES6 class:

class Person {
constructor(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
}

Inheritance is done with an extends keyword. The following sample code shows an Employee class that inherits a Person class. Therefore, it inherits all fields from the parent class and can have its own fields that are specific to the employee. In the constructor, we first call the parent class constructor by using the super keyword. That call is required and you will get an error if it is missing:

class Employee extends Person {
constructor(firstName, lastName, title, salary) {
super(firstName, lastName);
this.title= title;
this.salary = salary;
}
}

Although ES6 is already quite old but it is still only partially supported by modern web browsers. Babel is a JavaScript compiler that is used to compile ES6 to an older version that is compatible with all browsers. You can test the compiler on the Babel website (https://babeljs.io). The following screenshot shows the arrow function compilating back to the older JavaScript syntax:

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

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