Use eval () to "spoof" JavaScript lexical scopes

Source: Internet
Author: User

We know that the so-called "lexical scope" is the way the code is written when the internal function can access variables outside the function, if there is a function outside the same name variable, then the function inside to get the same name variable value will be masked out of the function of the same name variable (originally two different variables, just the same name.) Also note that the same scope is the same variable, so do not repeat the declaration, otherwise the second declaration will be ignored).

Use eval () to "spoof" the lexical scope:

function foo (str) {    eval (str);    Console.log (a);} var a=100; foo ("var a=12");   //  A

According to the logic should output 100, can actually output is 12, because Eval can cause Var a=12; This statement is as if it were in the same position as eval (). This code actually creates a variable B in the Foo function, so the variable b outside of the function is naturally masked.

eval () can insert code dynamically, but it actually has an impact on performance, so it's best not to use it.

Use eval () to "spoof" JavaScript lexical scopes

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.