JavaScript:全球范围 [英] JavaScript: global scope

查看:73
本文介绍了JavaScript:全球范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在,我创建了一个包含许多函数的.js文件,然后将其链接到我的html页面。这是有效的,但我想知道在我的页面中插入js以及避免与范围冲突的最佳方法(良好做法)...
谢谢。

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.

推荐答案

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

You could wrap them in an anonymous function like:

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

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

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:

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('jack', 'jill');

这篇关于JavaScript:全球范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆