in terms of memory usage and efficency, which one is better to use, a variable or WITH keyword?
For example:
var a = document.getElementById("divVar");
开发者_如何学Ca.style.font="bold 13px verdana";
a.style.color="#F00";
...
with(document.getElementById("divWith")){
style.font="bold 14px Georgia";
style.color="#00F";
...
}
Which one do you think is better?
with()
is considered harmful by Mr Crockford.
The reason? It is very easy to clobber existing variables, if the property you think exists doesn't, for example.
From the article...
If you can’t read a program and be confident that you know what it is going to do, you can’t have confidence that it is going to work correctly. For this reason, the with statement should be avoided.
The compromise is your first example.
usage and efficiency I would go with a var because your micro-optimizing and like alex said it's safer in the case of a type. Plus syntax editors won't catch it because it will think all the properties are global
you look it up once in either case- but the thing that uses resources is assigning and then rendering successive style property changes.
If you like efficiency, stay out of an element's inline style, or if you insist, make all the changes at once-
document.getElementById("divWith").style.cssText+= "font:13px verdana bold;color:#f00";
(to work properly x-browser, font shorthand should begin with the size and then family, with the other properties in any order.)
精彩评论