Classes
Learn how JavaScript classes offer us a new way to implement inheritance and object-oriented programming. Master the new syntax and see how we can leverage it to write more elegant code. Learn how easy it makes inheritance and what the JavaScript engine does for us with this new syntax.
We'll cover the following...
Classes in JavaScript are nothing more than special functions. They are created by using the class
keyword and being given a name. Like a normal function, when invoked with new
, a class returns an object.
class Person {}const alex = new Person();console.log(alex); // -> Person {}
Class constructor
Classes have a special method on them called constructor
. This is the method that is invoked when the class is invoked. Think of the constructor
method as the function body of the class.
We add methods on a class as if it were an object.
class Person {constructor(first, last, age = 25) {this.firstName = first;this.lastName = last;this.age = age;}}const alex = new Person('Alex', 'Smith');console.log(alex);// -> Person { firstName: 'Alex', lastName: 'Smith', age: 25 }
We can see that calling new Person()
results in the class ...