For people like me who didn't learn JavaScript systematically at first, the first feeling when I saw the with thing was excitement - I no longer have to write "element.style.xxx = ..." repeatedly, I only need to
view plaincopy to clipboardprint?
with (element.style) {
xxx = ...;
yyy = ...;
...
}
with (element.style) {
xxx = ...;
yyy = ...;
...
}But as an interpreted language, JavaScript needs to determine what xxx/yyy is at runtime. For each name (not just assigned, but also read variables!) it will first look for the properties of the object in with brackets, then local variables, and finally global variables. Before the popularity of JavaScript virtual machines and JIT technology, this kind of performance issue requires great attention.
The correct approach is to make a local variable cache for element.style:
view plaincopy to clipboardprint?
vares = element.style;
es.xxx = ...;
es.yyy = ...;
...
var es = element.style;
es.xxx = ...;
es.yyy = ...;
...This not only reduces the code size relatively, but also performs much better than element.style.xxx = ....