今天我們將講解JavaScript的Scope Chain作用原理
當JavaScript訪問變數時,會先在當前Scope尋找,倘若找不到就會再往外層找,就這樣一路找到Global scope(最外層),這個過程就被稱為Scope chain
const myName = "Jeremy";
function scope1() {
const age = 27;
if (age >= 25) {
const decade = age / 10;
var location = "Taichung";
}
function scope2() {
const job = "Programmer";
console.log(`${myName} is a ${age}-old ${job}`);
}
scope2();
}
scope1(); // Jeremy is a 27-old Programmer
在scope2裡頭的console.log得知
console.log(`${myName} is a ${age}-old ${job}`);
一共會需要訪問三個變數(myName、age、job)
變數名稱 | 讀取機制 |
---|---|
myName | 屬於global scope,因此在程式碼任何處都可讀取到 |
age | 定義於scope1這個外層函式(scope2是定義在scope1裡),因此藉由scope chain向外可讀取到 |
job | 本身就是在scope2 function內宣告的,屬於function scope |
需注意Scope chain只會向外層尋找,並不會向『內層或同層』尋找
若要尋找『同層』的decade變數(if function和scope2屬於同一層,並無父子關係):
const myName = "Jeremy";
function scope1() {
const age = 27;
if (age >= 25) {
const decade = age / 10;
var location = "Taichung";
}
function scope2() {
const job = "Programmer";
console.log(`${myName} is a ${age}-old ${job} ${decade}`); //新增decade變數
}
scope2();
}
scope1(); // Uncaught ReferenceError: decade is not defined
若更改console.log位置至scope1,要讀取內層的『job』變數
const myName = "Jeremy";
function scope1() {
const age = 27;
console.log(`${myName} is a ${age}-old ${job}`); //更改位置至此
if (age >= 25) {
const decade = age / 10;
var location = "Taichung";
}
function scope2() {
const job = "Programmer";
}
scope2();
}
scope1(); // Uncaught ReferenceError: job is not defined