gpt4 book ai didi

javascript - 匿名函数和变量作用域

转载 作者:行者123 更新时间:2023-11-28 20:17:39 25 4
gpt4 key购买 nike

我正在阅读一篇关于 requestAnimationFrame here 的文章,我意识到我在跟踪变量的范围和持久性方面遇到了困难。下面的代码稍作修改:

(function() {

//Note: lastTime is defined up here.
var lastTime = 0;

var vendors = ['ms', 'moz', 'webkit', 'o'];

//Okay, so they're trying to set window.rAF to the appropriate thing based on browser
for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
window.cancelRequestAnimationFrame = window[vendors[x]+
'CancelRequestAnimationFrame'];
}

//...and if that doesn't work, turn it into a setTimeout
if (!window.requestAnimationFrame)
window.requestAnimationFrame = function(callback, element) {

//I guess this is a way to make sure that the wait time
//between renders is consistent

var currTime = new Date().getTime();
var timeToCall = Math.max(0, 16 - (currTime - lastTime));
var id = window.setTimeout(function() { callback(currTime + timeToCall); },
timeToCall);

lastTime = currTime + timeToCall;

//Wait. They just assigned lastTime a value.
//Why is this going to persist between calls to window.rAF?
//The variable lastTime was defined inside this function, not in the window.

return id;
};

if (!window.cancelAnimationFrame)
window.cancelAnimationFrame = function(id) {
clearTimeout(id);
};
}())

我的猜测是这与放在括号内的函数有关,但是如何呢?使用这种编码风格可以实现什么效果以及我还能期待什么其他效果?我应该开始更频繁地使用它吗?如果是,那么什么时候?

最佳答案

这里的变量lastTime是通过closure捕获的。这意味着它在定义它的函数范围之外保持事件状态。

只要匿名函数体引用其自身范围之外的变量,就会创建闭包。闭包在 JavaScript 中非常有用,因为它们允许您维护状态而不将其全部公开到全局。

举一个简单的例子,

function foo() {
var count = 0;

setInterval(function bar() {
console.log(count++);
}, 100);
}

通过关闭此处的 count 变量,我可以在 setInterval 中使用它,而无需将 count 暴露给全局范围,否则我会这样做要做的事。

关于javascript - 匿名函数和变量作用域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18923531/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com