我的回答是关于全局变量。正如其他人也提到的那样,您的全局变量可以被加载到页面中的每个脚本(您的或其他库)使用/访问。另请注意,在浏览器中使用JavaScript时,您自定义的变量/函数位于“窗口”对象下。
而不是创建大量的全局变量/函数也可能是一个选项创建一个应用程序范围的全局变量。然后可以根据需要添加其他全局元素(变量甚至函数作为属性到这个对象)。您可以进一步采取这一措施,并为每个特定任务创建子属性。这将有助于保持代码清洁,并使其他人通过提供一种子分组来查看代码更容易理解。
举个例子
var myapp = {};
//creating a global mathmodule property under myapp that does all the math related work
myapp.mathmodule = {};
myapp.mathmodule.myvariable1 = 7;
myapp.mathmodule.myvariable2 = 3;
myapp.mathmodule.add = function() {
myapp.mathmodule.sumvalue =
myapp.mathmodule.myvariable1+myapp.mathmodule.myvariable2;
};
myapp.mathmodule.substract = function() {
myapp.mathmodule.differencevalue =
myapp.mathmodule.myvariable1 - myapp.mathmodule.myvariabl2;
};
//creating a global logmodule property under myapp that does all the logging work
myapp.logmodule ={};
myapp.logmodule.defaultmessage = "Default Values";
myapp.logmodule.logresults = function() {
console.warn('myapp.mathmodule.sumvalue:'+window.myapp.mathmodule.sumvalue);
console.warn('myapp.mathmodule.sumvalue again:'+myapp.mathmodule.sumvalue);
console.warn('myapp.mathmodule.differencevalue:'+window.myapp.mathmodule.differencevalue);
console.warn('myapp.mathmodule.differencevalue again:'+myapp.mathmodule.differencevalue);
};
myapp.logmodule.logdefaultvalues = function() {
console.log(myapp.logmodule.defaultmessage);
console.log('myapp.mathmodule.myvariable1:'+myapp.mathmodule.myvariable1);
console.log('myapp.mathmodule.myvariable2:'+myapp.mathmodule.myvariable2);
};
//你可以使用功能,如
myapp.mathmodule.add();
myapp.mathmodule.substract();
myapp.logmodule.logresults();
myapp.logmodule.logdefaultvalues();
在文件的顶端创建无VAR一个新的变量可能不会太糟糕,但中使用它一个函数肯定是令人困惑的(任何读你代码的人都不能确定你是否真的打算从你的函数中创建一个全局变量,而无需彻底读取我们的代码),并可能导致不可预知的结果。 JavaScript有两个作用域“功能级”和“全局”,如果你不在函数中使用'var'关键字,你定义的任何变量都在全局范围内创建,尽管你的任务可能在一个函数内。现在创建的变量现在可以通过应用程序中的任何代码访问/操作。
您可以尝试使用立即调用函数表达式(IIFE)在JavaScript中模拟块范围。我最近介绍了这个术语。
和退房更多的http://en.wikipedia.org/wiki/Immediately-invoked_function_expressionhttp://benalman.com/news/2010/11/immediately-invoked-function-expression
//if the code below followed the code at the top
//anything defined within this function is not exposed elsewhere
(function() {
var myapp = "Trying to overide the global myapp value";
console.log("Testing myapp value in an iife:",myapp);
console.log('Global myapp still accessible via window object:',window.myapp);
}());
console.log('myapp value outside of iife is the global value:',myapp);
输出将
Testing myapp value in an iife: Trying to overide the global myapp value
Global myapp still accessible via window object: Object {mathmodule: Object, logmodule: Object}
myapp value outside of iife is the global value: Object {mathmodule: Object, logmodule: Object}
来源
2013-07-04 19:59:08
PJR
请只问一个问题。 -1 – Doorknob