this series as effective JavaScript 's reading notes.
Item 9 : Avoid using with Key Words
Focus:
- Design with The keyword is intended to make the code concise, but it has the opposite effect, such as:
function f (x, Y) {with (Math) {return min (round (x), sqrt (y));//Ambiguous references}}
In the code above, the min round sqrt are math method.
if Math object does not have the method specified above, the with outside The scope of the search to find the method.
so if Math there are two fields on the object, namely x and the y :
math.x = 0; MATH.Y = 0;f (2, 9); 0
you can see that the result of the final call is 0 .
- The compiler is also unable to optimize the code, reducing the Property The search Speed
- a with The alternative is to give the variable the shortest possible name, and then use the usual way of doing it, such as:
function f (x, y) {var min = math.min, round = math.round, sqrt = Math.sqrt;return min (round (x), sqrt (y));}
Summarize:
- Avoid using with Key Words
- For frequently used objects, use the shortest possible variable name
- explicitly bind to an Object on the Property to the local variable , rather than using with
Effective JavaScript Variable Scope Item 10 Avoid using the WITH