$.post (ajaxUrl, {action:'get_seconds_to_next_cron'}, function (data) {
countdown = data + 600; //is this in global scope now?
setInterval('updateClock();',1000 );
},'json');
function updateClock() {
countdown--;
console.log(countdown); //output for verification
}
嗨,[第一个 stackoverflow 问题],上面是链接到我们的服务器时间和 cron 作业的购物车计时器的解决方案。
我担心倒计时会成为全局命名空间的一部分,因此不是最佳实践等。
下面是一些测试代码,尝试以不同的方式进行设置,以便(也许)在范围方面做得更干净。
var myWrapper = {
count: 600,
passCount : 'myWrapper.myCount(' +this.count+ ')',
myCount: function() {
this.count--;
console.log(this.count); //output for verification
},
setCounter: function() {
setInterval(this.passCount, 1000);
}
};
myWrapper.setCounter();
我对范围的理解充其量只是中等,因此任何反馈都会很有趣并且可能对我的理解有所帮助。
谢谢。
最佳答案
您可以将 updateClock()
转换为 anonymous function那closes over 倒计时
:
$.post(ajaxUrl, { action: 'get_seconds_to_next_cron' }, function(data) {
var countdown = data + 600; // This doesn't need to be global.
window.setInterval(function() {
countdown--; // Refers to the outer `countdown` variable.
console.log(countdown);
}, 1000);
}, 'json');
关于javascript - 帮助避免全局命名空间 - 两个例子 - 哪个更好?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4289294/