setInterval("/*some code*/",time)和setInterval(function(){/*some code*/},time)

Ran*_*lue 0 html javascript

我的印象是

setInterval("/*some code*/", time)
Run Code Online (Sandbox Code Playgroud)

相当于

setInterval(function() {
   /*some code*/
}, time)
Run Code Online (Sandbox Code Playgroud)

显然不是!请比较以下(完整的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>
Run Code Online (Sandbox Code Playgroud)

<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>
Run Code Online (Sandbox Code Playgroud)

这两个动画(第一个从这里开始)是不同的.

为什么这两个结构不相同?

:至少有三个不同之处

  1. 可变范围
  2. 性能
  3. 字符串字符转义

T.J*_*der 6

我没有研究过混淆代码,但是使用字符串和函数的区别在于setTimeout或是setInterval代码运行的范围.此外,当您使用字符串时,某些引擎可能也无法进行优化.

  • 传入字符串时,它在全局范围内运行.

  • 当您传入函数时,它将在其定义的范围内运行.

这会影响代码的范围,这会影响代码的作用.

这是一个没有混淆的例子:Live copy | 资源

(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);
}
Run Code Online (Sandbox Code Playgroud)