I want to write a utility class that will hold several methods that will be used throughout my code.
我想编写一个实用程序类,它将包含将在我的代码中使用的几种方法。
say Util.sayHi("Maxim") // Hi Maxim
but I want to try avoid pulling the global scope, and the possibility that someone would override my method.
比较Util.sayHi(“Maxim”)//你好Maxim,但我想尝试避免拉动全局范围,以及有人会覆盖我的方法的可能性。
I see jQuery has a solution to this problem https://learn.jquery.com/using-jquery-core/avoid-conflicts-other-libraries/ how do they do that?
我看到jQuery有一个解决这个问题的方法https://learn.jquery.com/using-jquery-core/avoid-conflicts-other-libraries/他们是如何做到的?
I'm working with React, and ES6 / ES7 transformers so new JS features are acceptable.
我正在使用React和ES6 / ES7变换器,所以新的JS功能是可以接受的。
1 个解决方案
#1
0
Well, since you are using ES6, the solution is trivial: use modules. They're designed to do exactly this.
好吧,既然您使用的是ES6,那么解决方案就很简单:使用模块。他们的目的就是做到这一点。
// util.js
export function sayHi(name) {
console.log("Hi "+name);
}
// somewhereelse.js
import * as Util from "util.js";
Util.sayHi("Maxim");
You're not polluting global scope at all, and the variables you are exporting are not writable from outside the module.
您根本不会污染全局范围,并且您导出的变量不能从模块外部写入。
#1
0
Well, since you are using ES6, the solution is trivial: use modules. They're designed to do exactly this.
好吧,既然您使用的是ES6,那么解决方案就很简单:使用模块。他们的目的就是做到这一点。
// util.js
export function sayHi(name) {
console.log("Hi "+name);
}
// somewhereelse.js
import * as Util from "util.js";
Util.sayHi("Maxim");
You're not polluting global scope at all, and the variables you are exporting are not writable from outside the module.
您根本不会污染全局范围,并且您导出的变量不能从模块外部写入。