with 语句通常用来缩短特定情形下必须写的代码量。使用with关键字来指定某个对象的一系列属性或者方法。
辟如:
with(Math){ document.write(PI); document.write(E); }
与下面等效:
document.write(Math.PI); document.write(Math.E);
的确可以减少代码量,但也见有地方写到“精简代码的方法却会使JavaScript的执行时间增加许多。因为它会去检查大括号内的每个变量是否是这个对象的属性或者方法”。也就是建议使用var而非with
于是无聊中做了下面实验:
<html> <head> <script type="text/javascript"> function withTest(){ /*三段代码执行效果相同,都是打印Math.E1000次*/ var start1,end1; start1=new Date().getTime() for(i=0;i<1000;i++) { document.write(Math.E); } end1=new Date().getTime() document.write("<br>"+(end1-start1)+"<br>")/*第一次时间,一般方法打印*/ var start2,end2; start2=new Date().getTime() var d=document var m=Math for(i=0;i<1000;i++) { d.write(m.E); } end2=new Date().getTime() document.write("<br>"+(end2-start2)+"<br>")/*第二次时间,使用var*/ var start3,end3; start3=new Date().getTime() with(document){ with(Math){ for(i=0;i<1000;i++) { write(E); } } } end3=new Date().getTime() document.write("<br>"+(end3-start3))/*第三次次时间,使用with*/ } </script> </head> <body onload="withTest()"> </body> </html>
三种方法1000次循环的结果时间只差不到10毫秒(一万次也只差几十毫秒,一万次在网页内打印不出来),所以时间代价可以忽略。。