javascript-使用嵌套类在ES6中模拟名称空间
作者:互联网
我有一个文件Services.js,正在尝试将所有单独的服务加载到其中.这些文件以单例形式公开.
Services.js
var Services = { };
export default Services;
然后,我想将Sample Service嵌套在Services下,因此可以调用例如Services.Sample.Operation()
`SampleService.js’
import Services from './Services';
Services.Sample = {
Operation: function() {
alert('operation!')
}
};
export default Services.Sample;
然后,我尝试导入:
import Services from './services/Services';
import SampleService from './services/SampleService';
alert(Services); // yields '[object object]'
alert(SampleService); // yields '[object object]'
alert(Services.Sample); // yields 'undefined' <--- This is the one I actually want to use
我如何获得它,所以我可以参考Services.Sample而不是tan SampleService.如何使SampleService嵌套在服务下?
解决方法:
您的方式行不通,因为您要在SampleService.js中导入Services.js,但是Services变量不是Services.js的“原始” Services变量.
我要做的是这样的:
SampleService.js:
SampleService = {
Operation: function() {
alert('operation!')
}
};
export default SampleService;
Services.js:
import SampleService from './SampleService';
var Services = { };
Services.Sample = SampleService;
export default Services;
接着:
import Services from './services/Services';
alert(Services);
alert(Services.Sample);
export default Services;
对于模块的基本(独立)依赖性和一致性,这对我来说似乎更有意义(定义Services可以在Services.js中执行的功能而不是SampleService.js,SampleService可以独立于Services,加载Services.js的模块应不依赖于SampleService.js,因为以后可能会更改,…).
标签:ecmascript-6,javascript 来源: https://codeday.me/bug/20191121/2048068.html