为了避免使用全局变量,我如何将代码包装到模块中? [英] How can I wrap code into a module in order to avoid using global variables?
问题描述
在我的以前的问题,我想到了以下工作代码,旨在通过替换< div id =test_css_id> ...< / div>
本身。以下代码中存在的两个AJAX请求的行为是重新加载相同的代码本身。
After my previous question, I come up to the following working code that is intended to refresh the DOM periodically by replacing the <div id="test_css_id">...</div>
itself. The behavior of both AJAX requests present in the below code is to reload the same code itself.
<div id="test_css_id">
<a id="link_css_id" href="test_url.html">LINK</a>
<script type="text/javascript">
var refreshTimer;
$('#link_css_id').click(function(event) {
event.preventDefault();
$.ajax({
url: $(this).attr('href'),
type: 'PUT',
success: function(data) {
clearInterval(refreshTimer);
$('#test_css_id').replaceWith(data); // Replaces all code including JavaScript with the response data (note: the response data is exactly the same as the code shown here).
}
});
});
$(document).ready(function() {
function refreshFunction(){
$.ajax({
url: 'test_url.html',
type: 'GET',
success: function(data) {
clearInterval(refreshTimer);
$('#test_css_id').replaceWith(data); // Replaces all code including JavaScript with the response data (note: the response data is exactly the same as the code shown here).
}
});
}
refreshTimer = setInterval(refreshFunction, 1000);
});
</script>
</div>
然而,正如接受的答案,有其他方法可以做[..]一种方法是将所有代码包装到一个模块中。我不是JavaScript的专家,但我想了解并了解更多。
However, as said by the author of the accepted answer, "there are other ways you can do it [..] one way is to wrap all of that code into a module". I am not expert in JavaScript but I would like to understand and learn it a little more.
如何将所有代码包装到模块中以避免使用全局变量?
How can I wrap all of that code into a module in order to avoid using global variables?
推荐答案
您当前的代码如下所示:
Your current code looks like this:
var refreshTimer; //a global variable
$(...).click(...);
$ b
To make refreshTimer not global, you need to put it inside a function:
function main(){
var refresherTimer; //this variable is now local to "main"
$(...).click(...);
}
main();
然而,这样做不会完全解决问题。虽然我们已经摆脱了全局变量,但是我们添加了一个新的main函数本身。
However, doing it this way won't solve the problem completely. While we did get rid of the global variables, we added a new one - the "main" function itself.
最后一个技巧是将main函数转换成一个匿名函数并直接调用它。这是着名的模块模式:
The final trick is to turn the "main" function into an anonymous function and invoke it directly. This is the famous "module pattern":
(function(){
var refreshTimer; //local variable to that anonymous function
$(...).click(...);
}()); //and here we call the function to run the code inside it.
一切附加的括号很重要。如果你只是 function(){}()
而不是(function(){}())
那么你将收到语法错误。
The extra parenthesis around everything are important. If you do just function(){}()
instead of (function(){}())
then you will get a syntax error.
这篇关于为了避免使用全局变量,我如何将代码包装到模块中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!