JavaScript:全局范围

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3265823/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 00:41:20  来源:igfitidea点击:

JavaScript: global scope

javascriptscopeglobal

提问by thomas

Nowdays, i create a .js file with a lot of functions and then I link it to my html pages. That's working but I want to know what's the best way (good practices) to insert js in my pages and avoid conflicts with scope... Thank you.

现在,我创建了一个具有很多功能的 .js 文件,然后将其链接到我的 html 页面。这是有效的,但我想知道在我的页面中插入 js 并避免与范围冲突的最佳方法(良好做法)是什么......谢谢。

回答by lucideer

You could wrap them in an anonymous function like:

您可以将它们包装在一个匿名函数中,例如:

(function(){ /* */ })();

However, if you need to re-use all of the javascript functions you've written elsewhere (in other scripts), you're better off creating a single global object on which they can be accessed. Either like:

但是,如果您需要重用您在其他地方(在其他脚本中)编写的所有 javascript 函数,最好创建一个可以访问它们的全局对象。要么像:

var mySingleGlobalObject={};
mySingleGlobalObject.someVariable='a string value';
mySingleGlobalObject.someMethod=function(par1, par2){ /* */ };

or the alternative, shorter syntax (which does the same thing):

或者另一种更短的语法(做同样的事情):

var mySingleGlobalObject={
  someVariable:'a string value',
  someMethod:function(par1, par2){ /* */ }
};

This can then be accessed later from other scripts like:

然后可以稍后从其他脚本访问它,例如:

mySingleGlobalObject.someMethod('Hyman', 'jill');

回答by ChaosPandion

A simple idea is to use one object that represents your namespace:

一个简单的想法是使用一个代表您的命名空间的对象:

var NameSpace = {
    Person : function(name, age) {

    }
};

var jim= new NameSpace.Person("Jim", 30);

回答by tcooc

The best way is to create a new scope and execute your code there.

最好的方法是创建一个新的范围并在那里执行您的代码。

(function(){
  //code here
})();

This is best used when the global scope is accessed at a minimum.

这在最少访问全局范围时最好使用。

Basically, this defines an anonymous function, gives it a new scope, and calls it.

基本上,这定义了一个匿名函数,给它一个新的作用域,然后调用它。

回答by Curtis

It's perhaps not the BEST way, but a lot of PHP systems (I'm looking at you, Drupal) take the name of their particular plugin and prepend it to all their function names. You could do something similar, adding the name of your capability to your function names - "mything_do_action()"

这可能不是最好的方法,但是很多 PHP 系统(我正在看着你,Drupal)采用他们特定插件的名称并将其添加到所有函数名称之前。您可以做类似的事情,将您的功能名称添加到您的函数名称中 - “mything_do_action()”

Alternately, you could take a more "OO" approach, and create an object that encapsulates your capability, and add all your functions as member functions on IT. That way, there's only one thing in global scope to worry about.

或者,您可以采用更“OO”的方法,创建一个封装您的能力的对象,并将您的所有功能添加为 IT 上的成员功能。这样,在全局范围内只需担心一件事。