1. Closure scope Exercises (1)

{
    function foo() {}
    foo = 1
}
console.log(foo) Function foo() {} function foo() {}
Copy the code
  • Older browsers “do not support block-level context”If judging body The for loop body {} blockThere’s no context.Older browsers only have global context and function execution private context

  • The new version of the browser is “ES3/ES5 compatible, ES6 compatible as well, so there are some very kinky mechanisms”,The occurrence of let/const/function in braces other than function/object braces separately forms a block-level private context. The variable promotion appears in other bracesFunction is no longer a declaration + definition, but just a declaration

2. Closure scope Exercises (2)

console.log(foo) // undefined
{
    console.log(foo) // function foo() {}
    function foo() {}
    console.log(window.foo) // function foo() {}
    foo = 1
    function foo() {} // Function special: all previous assignments to foo gave the global a copy of global foo = 1
}
console.log(foo) / / 1
Copy the code

3. Closure scope Exercises (3)

{
    function foo() {}
    foo = 1
    function foo() {}
    foo = 2
}
console.log(foo) / / 1
Copy the code

4. Closure scope Exercises (4)

var x = 1
function func(x, y = function anonymous1() { x = 2 }) {
    x = 3
    y()
    console.log(x) / / 2
}
func(5)
console.log(x) / / 1
Copy the code

5. Closure scope Exercises (5)

var x = 1
function func(x, y = function anonymous1(){ x = 2 }){
    console.log(x) / / 5
    var x = 3
    y()
    console.log(x) / / 3
}
func(5)
console.log(x) / / 1
Copy the code
  • If the function applies (' parameter assignment default ') "regardless of what the assignment is and whether the argument is passed"

  • Var/let/const; const; var/let/const;

  • In addition to the fact that the function execution takes place in a private context, "the step ends when the parameter is assigned." The function body and the code in it are treated as a 'new block-level context'. If the variable declared in the block-level context is identical to the parameter in the function private context, the value of the parameter is synchronized to the block-level context variable before the block-level context code executes.

6. Closure scope Exercises (6)

var x = 1
function func(x, y = function anonymous1() { x = 2} ){
    var x = 3
    var y = function anonymous2() { x = 4 }
    y()
    console.log(x) / / 4
}
func(5)
console.log(x) / / 1
Copy the code