Friday, December 23, 2016

JavaScript Evolution ESMAScript 6 - Module

In this section, we learn about using Module to encapsulate classes.

To export classes, use the export syntax with the class name inside curly braces.

flash-message.js
class FlashMessage {

  constructor(message) {
    this.message = message;
  }

  renderAlert() {
    alert(`${this.message} from alert`);
  }

  renderConsole() {
    console.log(`${this.message} from log`);
  }

}

export {FlashMessage} // Export class to outside world.
To import the class, we must use the same export name.

app.js
import {FlashMessage} from './flash-message';

let flash = new FlashMessage('Hello');
flash.renderAlert(); // Alert -> Hello from alert
flash.renderConsole(); // Console -> Hello from log

No comments:

Post a Comment