在ES6中定义类时,它在全局范围内可用,您可以使用新的ES6支架机箱来防止它:
{ class Car { constructor(make) { this.make = make; this.currentSpeed = 25; } getSpeed(){ console.log(this.make + ' is going ' + this.currentSpeed + ' mph.'); } } window.MYNAMESPACE.Car = Car; }
我有多个js文件,每个文件都有自己的类定义,我在全球范围内通过MYNAMESPACE使这些类可用.因此,从任何地方创建一辆新车看起来像:
var myCar = new MYNAMESPACE.Car();
我怎么能用ES6模块呢?这是可能的,还是值得推荐的?
您应该使用ES6导出和导入,而不是使类在全局范围内可用.
// 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();
阅读es6模块语法
http://www.2ality.com/2014/09/es6-modules-final.html
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