Why do some variables declared using let inside a function become available in another function, while others result in a reference error?

前端 未结 8 1123
说谎
说谎 2021-01-30 03:45

I can\'t understand why variables act so strange when declared inside a function.

  1. In the first function I declare with let the variabl

8条回答
  •  说谎
    说谎 (楼主)
    2021-01-30 04:25

    Main difference is scoping rules. Variables declared by var keyword are scoped to the immediate function body (hence the function scope) while let variables are scoped to the immediate enclosing block denoted by { } (hence the block scope). And when you say

    c = 10;
    b = c;
    let a = b;
    

    c and b have the life span as fun have but a only have block span and if you try to access a by referencing it always show error but c and b are globally so they don't.You'll notice that no matter how many variables you add to your chain, it will only be the first (a) that causes the error.This is because "let" scopes your variable to the block (or, "locally", more or less meaning "in the brackets") in which you declare it.If you declare a variable without "let", it scopes the variable globally.So, in the function where you set your variables, everything gets the value 10 (you can see this in the debugger if you put a break-point). If you put a console log for a,b,c in that first function, all is well.But as soon as you leave that function, the first one (a)--and again, keep in mind, technically in the order of assignment, it is the last one-- "disappears" (again, you can see this in the debugger if you set a break-point in the second function), but the other two (or however many you add) are still available.

提交回复
热议问题