Effective JavaScript Variable Scope Item 10 Avoid using the WITH

Source: Internet
Author: User
Tags variable scope

this series as effective JavaScript 's reading notes.

Item 9 : Avoid using with Key Words

Focus:

    1. 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 .

    1. The compiler is also unable to optimize the code, reducing the Property The search Speed
    2. 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:

  1. Avoid using with Key Words
  2. For frequently used objects, use the shortest possible variable name
  3. 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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.