我看到这个用法很多,有人告诉我把函数引用放在引号中是不好的,因为setTimeout
/setInterval
会评估该引用。这两者之间的实际区别是什么,为什么经常看到这种用法,即使应该普遍知道这种方法是错误的?
我看到这个用法很多,有人告诉我把函数引用放在引号中是不好的,因为setTimeout
/setInterval
会评估该引用。这两者之间的实际区别是什么,为什么经常看到这种用法,即使应该普遍知道这种方法是错误的?
People may not realize they can use the unquoted form.
The name referenced in the string may not yet be defined.
The quoted form gives you delayed execution:
setTimeout("myFunction(1, 'hello')", 100)
is easier to understand than:
setTimeout(function () { myFunction(1, 'hello') }, 100)
and this doesn't do what the author wants:
setTimeout(myFunction(1, 'hello'), 100)
myFunction
返回一个函数或可评估的字符串。 - kojiro这两种形式之间有两个主要的区别:
setTimeout("myFunc()", 100);
并且
setTimeout(myFunc, 100);
x = myFunc();
或者你会写成:
x = eval("myFunc()");
eval()
是一个相当重量级的东西,应该只在没有其他更好的方法时使用它。顺便说一下,this jsPerf comparison 表明 eval()
版本慢了96%。 在某些情况下,性能可能无关紧要,但是您可以了解到它效率低下的程度。
我敢打赌它也可以防止内存泄漏。
不会泄漏 X:
var x = $("loading");
setTimeout("createTree(1);", 0);
泄漏的 X:
var x = $("loading");
setTimeout(function(){createTree(1);}, 0);
setTimeout()
不应该对x
发生任何影响。 - jfriend00function runme(){var x=1; setTimeout("alert(x);",1000)} function runme2(){var x=1; setTimeout(function(){alert(x);},1000)}
调用 runme()
会抛出错误,因为x超出了范围,可以进行垃圾回收。调用 runme2()
将会弹出x,因为它在范围内,在1秒钟之后才能进行垃圾回收。 - Kernel James