Defining classes

Let's start with the basics and look at how classes are defined in modern JS. Afterwards, we'll move to other features that are interesting, but that you might not use that often. To define a class, we simply write something like the following:

// Source file: src/class_persons.js

class Person {
constructor(first, last) {
this.first = first;
this.last = last;
}

initials() {
return `${this.first[0]}${this.last[0]}`;
}

fullName() {
return `${this.first} ${this.last}`;
}
}

let pp = new Person("Erika", "Mustermann");
console.log(pp); // Person {first: "Erika", last: "Mustermann"}
console.log(pp.initials()); // "EM"
console.log(pp.fullName()); // "Erika Mustermann"

The new syntax is much clearer than using functions for constructors, as in older versions of JS. We wrote a .constructor() method, which will initialize new objects, and we defined two methods, .initials() and .fullName(), which will be available for all instances of the Person class.

We are following the usual convention of using an initial uppercase letter for class names and initial lowercase letters for variables, functions, methods, and so on.
..................Content has been hidden....................

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