10

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?

1 Answer 1

10

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:
7
  • 1
    Thanks! A simple example can go a long way! Those links tend to overload the poor reader with the world's most elaborate examples :)
    – Kokodoko
    Commented Jan 5, 2016 at 13:48
  • By the way, can I leave out the { } anonymous brackets at the start/end of each class? What is the best way to init a main app.js after window.onload?
    – Kokodoko
    Commented Jan 5, 2016 at 14:28
  • @Kokodo you can leave them out. For the initing you can just include a js file with <script>-tags, in which you import the App itself from "./app.js" and call the init after window.onload (or just bake it into app.js) like you normally would do.
    – Pete TNT
    Commented Jan 5, 2016 at 14:40
  • OK, and then I need to convert ES6 > ES5 and use something like Browserify to get the 'require' keyword working in current browsers, right? (just trying to get my workflow in order :)
    – Kokodoko
    Commented Jan 5, 2016 at 15:04
  • Yup. Look into Babelify, it does the conversion during the browserify process.
    – Pete TNT
    Commented Jan 5, 2016 at 16:08

Not the answer you're looking for? Browse other questions tagged or ask your own question.