You do not know [2] javaScript notes javaScript scoping rules

First, what is the lexical scoping?

Lexical scope is defined in the scope of the lexical stage, the code is written by block variables and scope decide where substantially lexical analyzer when processing code remains unchanged scope.

Second, lexical scoping Features

  • Entirely defined by the position of the code during the write function declarations

  • Find in just one lexical scoping identifier (foo.bar.baz, just trying to find the foo identifier)

Third, how to modify the lexical scoping runtime?

  1. eval()

    function foo ( STR, A) { the eval ( STR) // foo function modifies the lexical scope Console. log ( A, B) } var B = 2; foo ( 'B = var. 3;', . 1); / / 1,3




    In strict mode eval (), have their own lexical scope

  2. with the var statement will be added to with which the scope, parameters did not object creates a new lexical scope

eval () will modify the scope and with at runtime, which undermines the ability js static analysis engine based on lexical at compile time, all a lot of use can affect the performance of the code

Four, javaScript scope

  • Function scope

Values ​​of all the variables belonging to the scope of the function of this function can be used and reused in the entire range of functions.

Function expression IIFE: (function foo () {}) (), it can be used to prevent contamination global scope

  • Global scope

  • Block-level scope

    with

    try/catch (ES3)

    let (ES6)

    const

V. Summary

javaScript lexical scoping rules to follow, there are currently some scope global scope, function scope and block-level scope, which is the most common function scope scoping unit. Lexical scoping has been determined at compile time under normal circumstances, if you modify the lexical scoping in runtime operation will affect the performance of the code.

Guess you like

Origin www.cnblogs.com/seny-33/p/12184887.html