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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With