我如何把所有这1200+行自定义javascript到一个闭包,所以没有全局变量

How do I put all this 1200+ line custom javascript into a closure so there are no global vars?

本文关键字:一个 闭包 全局变量 javascript 1200+ 自定义      更新时间:2023-09-26

标题基本上解释了问题。代码包括jQuery和$(document).ready(function(){...}),其中包含800多行和400多行函数声明。也有一些全球知名人士名列前茅。我想把所有这些放到闭包中,而不影响(我应该说影响?)代码当前的功能(或者至少希望很少)!

不知道代码是什么样子的

(function(window, $) {
   // your code here
}(window, jQuery));

但是如果一切都已经在$(document).ready()中,那么你真的不需要做任何事情。

$(document).ready(function已经将你所有的代码包装在一个函数中,并将其隐藏在全局作用域中。

$(document).ready(function(){
  var closurevar=22;// will be available withint 
             // the function body but not outside
  console.log(closurevar);//will be 22
  globalVar=33;//not having the var keyword puts this
               // in global scope
  window.globalVar2=44;//more correct way to define global var
                       // jquery defines $ in this way.
});
console.log(closurevar);//will be undefined
// globalVar won't be available until document ready is executed
console.log(globalVar);// will be undefined but will be set after
                       // document.ready has executed