[英]How can I wrap code into a module in order to avoid using global variables?
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. 在上一个问题之后 ,我提出了以下工作代码,该代码旨在通过替换
<div id="test_css_id">...</div>
本身来定期刷新DOM。 The behavior of both AJAX requests present in the below code is to reload the same code itself. 以下代码中存在的两个AJAX请求的行为是重新加载相同的代码本身。
<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>
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.
我不是JavaScript方面的专家,但是我想多了解一些。
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(...);
To make refreshTimer not global, you need to put it inside a function: 要使refreshTimer不是全局的,您需要将其放入函数中:
function main(){
var refresherTimer; //this variable is now local to "main"
$(...).click(...);
}
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. 最后一个技巧是将“ main”功能转换为匿名功能并直接调用它。 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.
The extra parenthesis around everything are important. 围绕所有内容的附加括号很重要。 If you do just
function(){}()
instead of (function(){}())
then you will get a syntax error. 如果仅使用
function(){}()
而不是(function(){}())
,则会出现语法错误。
这是 JavaScript中模块模式的不错描述。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.