作用域
編程語言中作用于域的定義
Scope refers to the visibility of variables. In other words, which parts of your program can see or use it.
譯為:作用域指的是變量的可見性鹉动, 換句話說僻族, 就是程序可以看見和使用的那部分變量。
JS中的作用域
JS采用的是詞法作用域(Lexical scope, static scope)
Lexical scoping (sometimes known as static scoping ) is a convention used with many programming languages that sets the scope (range of functionality) of a variable so that it may only be called (referenced) from within the block of code in which it is defined. The scope is determined when the code is compiled.
譯為: 詞法作用域(有時(shí)也稱為靜態(tài)作用域)是許多編程語言使用的一種約定命爬,它設(shè)置變量的范圍笔宿,以便于只能從定義它的代碼塊中調(diào)用它律姨。作用域在代碼編譯階段決定米苹。
當(dāng)然有靜態(tài)作用域就會(huì)有動(dòng)態(tài)作用域,這里不多做討論忍啸。
舉個(gè)例子
let a = 'global'
function showA() {
console.log(a)
}
function foo() {
let a = 'foo'
showA()
}
foo() // 'global'
例子中仰坦, 在foo方法中調(diào)用了showA方法,最終打印出來的結(jié)果居然是'global'! 為什么计雌? showA方法在編譯階段就將a指向了全局中的a悄晃。牢記那句話作用域在代碼編譯階段決定!