Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use ES6 modules instead of namespaces in the global scope?

When defining a class in ES6, it becomes available in the global scope, which you can prevent with the new ES6 bracket enclosure:

{
  class Car {
    constructor(make) { 
        this.make = make;
        this.currentSpeed = 25;
    }

    getSpeed(){
          console.log(this.make + ' is going ' + this.currentSpeed + ' mph.');
    }
  }
  window.MYNAMESPACE.Car = Car;
}

I have multiple js files, each with their own class definition, and I make the classes available via MYNAMESPACE in the global scope. So creating a new car from anywhere looks like:

var myCar = new MYNAMESPACE.Car();

How could I use ES6 modules for this? Is that even possible, or recommendable?

like image 457
Kokodoko Avatar asked Jan 04 '16 14:01

Kokodoko


1 Answers

You should be using ES6 exports and imports instead of making the classes available in global scope.

// car.js
class Car {
  constructor(make) { 
        this.make = make;
        this.currentSpeed = 25;
  }

  getSpeed(){
    console.log(this.make + ' is going ' + this.currentSpeed + ' mph.');
  }
}

export default Car;

// foo.js    
import Car from "./car"

var car = new Car("ford");
car.getSpeed();

Read up on es6 module syntax from

  1. http://www.2ality.com/2014/09/es6-modules-final.html
  2. MDN:
    • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/class
    • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import
    • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export
like image 131
Pete TNT Avatar answered Oct 06 '22 18:10

Pete TNT