w3resource

Exporting and Extending Classes in JavaScript


Exporting Classes:

Write a JavaScript program to create a module that exports a class. Instantiate and use the class in another file.

Solution-1: Using Named Exports

Code:

File: Person.js

This file contains the Person class.

//File: Person.js
//This file contains the Person class.

// Person.js
// Defining and exporting the Person class
export class Person {
  constructor(name, age) {
    this.name = name; // Assigns name
    this.age = age; // Assigns age
  }

  introduce() {
    // Method to introduce the person
    return 'Hi, I'm ${this.name}, and I'm ${this.age} years old.';
  }
}

File: main.js

This file demonstrates using the exported class.

// main.js  
// Importing the Person class
import { Person } from './Person.js';

// Instantiating and using the class
const pers = new Person('Agenor Tigerlily', 30);
console.log(pers.introduce());

Output:

Hi, I'm Agenor Tigerlily, and I'm 30 years old.

Explanation:

  • The Person class is defined in Person.js and exported as a named export.
  • main.js imports the Person class using named imports.
  • An instance of the class is created, and its method is called to log the introduction.

Solution-2: Using Default Exports

Code:

File: Person.js

// Person.js
// Defining and exporting the Person class
export class Person {
  constructor(name, age) {
    this.name = name; // Assigns name
    this.age = age; // Assigns age
  }

  introduce() {
    // Method to introduce the person
    return `Hi, I'm ${this.name}, and I'm ${this.age} years old.`;
  }
}

File: main.js

// main.js  
// Importing the Person class
import { Person } from './Person.js';

// Extending the Person class
class Employee extends Person {
  constructor(name, age, position) {
    super(name, age); // Calling the parent constructor
    this.position = position; // Adding a new property
  }

  work() {
    // Method specific to the Employee class
    return `${this.name} is working as a ${this.position}.`;
  }
}

// Instantiating and using the extended class
const alice = new Employee('Viola Philomela', 28, 'Software Engineer');
console.log(alice.introduce());  
console.log(alice.work());  

Output:

Hi, I'm Viola Philomela, and I'm 28 years old.
Viola Philomela is working as a Software Engineer.

Explanation:

  • The Person class is defined in Person.js and exported as a named export.
  • main.js imports the Person class and extends it to create an Employee class.
  • The Employee class adds a new property position and a new method work.
  • An instance of Employee is created and both the inherited and new methods are called.

Improve this sample solution and post your code through Disqus

Previous: Import JSON Data in JavaScript Modules.
Next: JavaScript Modules with Tree Shaking Techniques.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.