Classes

Defining a Class

ES6 Class Syntax

ES6 Class

Inheritance

We can make a child class of another class, parent class, by using the extend keyword

class Cat extends Animal {

}

ES5 Class Syntax

ES5 Class

Importing and Exporting Modules

Importing and Exporting Demo

Importing built-in Node modules or npm-installed modules

const mocha = require('mocha');

Exporting modules from your own code

class Person {
  // ...
}
const hello = 'hello';
module.exports = {
  Person,
  hello
};

is the same as:

exports.Person = class Person {
  // ...
};
exports.hello = 'hello';

Importing modules from your own code

const tax = require('../util/tax'); // will look into the util folder for tax.js

in the file ../util/people.js:

class Person {
  // ...
}
const hello = 'hello';
module.exports = {
  Person,
  hello
};

can import Person into ./index.js by:

const { Person } = require('../util/people.js');

JavaScript Classes Learning Objectives

  1. Define a constructor function using ES5 syntax.
  2. Define a method on the prototype of a constructor function using ES5 syntax.
  3. Declare a class using ES6 (ES2015) syntax.
  4. Define an instance method on a class (ES6).
  5. Define a static method on a class (ES6).
  6. Instantiate an instance of a class using the new keyword.
  7. Implement inheritance using the ES6 extends syntax for an ES6 class.
  8. Utilize the super keyword in a child class to inherit from a parent class.
  9. Utilize module.exports and require to import and export functions and class from one file to another.