我的印象是
setInterval("/*some code*/", time)
相当于
setInterval(function() {
/*some code*/
}, time)
显然不是!请比较以下内容(完整 HTML):
<pre id=p><script>n=setInterval("for(n+=7,i=k,P='p.\\n';i-=1/k;P+=P[i%2?(i%2*j-j+n/k^j)&1:2])j=k/i;p.innerHTML=P",k=64)</script>
和
<pre id=p><script>n=setInterval(function() { for(n+=7,i=k,P='p.\\n';i-=1/k;P+=P[i%2?(i%2*j-j+n/k^j)&1:2])j=k/i;p.innerHTML=P },k=64)</script>
这两个动画(第一个动画取自 here )是不同的。
为什么这两个构造不等价?
答案:至少存在三个差异
- 变量范围
- 性能
- 字符串字符转义
最佳答案
我还没有研究过混淆的代码,但是使用字符串和带有 setTimeout
或 setInterval
的函数之间的区别在于代码运行的范围。另外,当您使用字符串时,某些引擎可能也无法优化。
当您传入字符串时,它会在全局范围内运行。
当您传入一个函数时,它会在定义它的范围内运行。
这会影响哪些变量在代码范围内,从而影响代码的功能。
(function() {
var foo = 42;
// This will say "undefined", because there is no global `foo`
setTimeout("display(typeof foo);", 0);
// This will say "number", because the function is closure over
// the current scope, whcih *does* have `foo`
setTimeout(function() {
display(typeof foo);
}, 0);
})();
function display(msg) {
var p = document.createElement('p');
p.innerHTML = String(msg);
document.body.appendChild(p);
}
关于javascript - setInterval ("/*some code*/", time) 和 setInterval(function() {/*一些代码*/}, time),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10364235/