简体   繁体   English

ES6:将变量保存到模块范围内

[英]ES6: Save variable into module scope

I'd like to know if and how it's possible to save the following config into my modules scope (think of the block below as one module): 我想知道是否以及如何将以下config保存到我的模块范围内(将下面的块视为一个模块):

var config = null;

var mySingleton = {
    init: function(config) {
        config = config; // Naming conflict!
    },

    printConfig: function() {
        console.log(config); // Undefined!
    }
};

export { mySingleton };

Unfortunately, a naming conflict occurs. 不幸的是,发生了命名冲突。 I'd need something like module.config = config; 我需要像module.config = config; .

Note: I'm using the es6-module-transpiler . 注意:我正在使用es6-module-transpiler

No. It's a simple variable, and not a global one (where it would be accessible as a property of the global object), so it just is shadowed and not available "namespaced". 不是。它是一个简单的变量,而不是全局变量(它可以作为全局对象的属性访问),因此它只是被遮蔽而且不可用“命名空间”。

You need to use a different name to resolve conflicts, which should be trivial and will cause no effects outside the module: 您需要使用其他名称来解决冲突,这应该是微不足道的,并且不会在模块外部产生任何影响:

var config = null;

var mySingleton = {
    init: function(conf) {
        config = conf;
    },
    printConfig: function() {
        console.log(config);
    }
};

export { mySingleton };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM