清单 4. 使用局部变量
- var myObj = … ..
- ..
- function process(){
- var doc = document;
- var images = doc.getElementsByTagName("img"),
- widget = doc.getElementsByTagName("input"),
- combination = [];
- for(var i = 0; i < images.length; i++){
- combination.push(combine(images[i], widget[2*i]));
- }
- myObj.container.property1 = combination[0];
- myObj.container.property2 = combination[combination.length-1];
- }
我们用局部变量“doc”取代全局变量“document”,这样可以改进性能,尤其是对于大量使用全局变量的函数里面。
再看如下代码:
清单 5. 慎用 with
- var myObj = … ..
- ..
- function process(){
- var doc = document;
- var images = doc.getElementsByTagName("img"),
- widget = doc.getElementsByTagName("input"),
- combination = [];
- for(var i = 0; i < images.length; i++){
- combination.push(combine(images[i], widget[2*i]));
- }
- with (myObj.container) {
- property1 = combination[0];
- property2 = combination[combination.length-1];
- }
- }
加上“with”关键字,我们让代码更加简洁清晰了,但是这样做性能会受影响。正如之前说的,当我们进入“with”代码块时,“combination”便从原来的层 1 变到了层 2,这样,效率会大打折扣。所以比较一下,还是使用原来的代码:
清单 6. 改进 with
- var myObj = … ..
- ..
- function process(){
- var doc = document;
- var images = doc.getElementsByTagName("img"),
- widget = doc.getElementsByTagName("input"),
- combination = [];
- for(var i = 0; i < images.length; i++){
- combination.push(combine(images[i], widget[2*i]));
- }
- myObj.container.property1 = combination[0];
- myObj.container.property2 = combination[combination.length-1];
- }