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:
Sign up to request clarification or add additional context in comments.

7 Comments

Thanks! A simple example can go a long way! Those links tend to overload the poor reader with the world's most elaborate examples :)
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?
@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.
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 :)
Yup. Look into Babelify, it does the conversion during the browserify process.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.