<1>全域性作用域
全域性作用域中定義的變數和方法都會被繫結到window
上(除了let
、const
)
var a =1;
//全域性變數
function
fnscope()
<2>塊級作用域
{}
包裹的就是塊級作用域(es6
新增的let
、const
定義的)
console.
log(a)
;//找不到 出了塊級作用域訪問不到a了
console.
log(b)
;//找不到
console.
log(a)
;//1if(
false
)console.
log(a)
;//undefined
}console.
log(init)
;// ? init() if(
false)}
console.
log(init)
;// ? init()
init =3;
}console.
log(init)
;// ? function init()
init =3;
console.
log(
'kuai'
, init)
;//? 3
}console.
log(init)
;//? function init()
init =3;
console.
log(init)
;//? 3
}console.
log(init)
;//? 4 輸出的是最後乙個函式的上乙個的值
functionfn(
)if(false)}
fn();
//?out 如果為true那麼就輸出inner
思考 init =3;
console.
log(init)
;// ?3
function
init()
init =5;
}console.
log(init)
;// ?3 因為取最後乙個函式的上乙個值
init =3;
console.
log(init)
;// ?3
function
init()
init =5;
function
init()
}console.
log(init)
;// ?5
<3>函式作用域
在function
函式中的就是函式作用域
function
fnscope()
fnscope()
//1console.
log(a)
;//找不到 出了函式作用域就訪問不到a了
functionfn(
)function
init()
}fn()
;// uncaught typeerror: fn is not a function
}init()
;/*因為函式作用域下fn會提公升,但如果為false的話,方法體不會提公升。所以最終變為了:
function init()
// fn為undefined
fn(); // uncaught typeerror: fn is not a function}*/
思考functionfn(
)function
init()
}fn()
;}init()
;//? inner
<4>詞法作用域
無論函式在**被呼叫,如何被呼叫,它的詞法作用域都只由函式被宣告時所處的位置決定(小技巧:除了this
定義和呼叫的值,其他都是在詞法作用域中),沒有this
var a =
123;
function
parent()
child()
;//321
return child
}const p =
parent()
;//無論呼叫位置在**p(
);//321
this
繫結的效果:
var a =
123;
function
parent()
child()
;//123 this指向window
return child
}const p =
parent()
;p()
;//123
作用域的理解
什麼是作用域 作用域就是一套規則,控制著變數和函式的可訪問範圍。作用域外無法引用作用域內的變數,離開作用域後,作用域的變數的記憶體空間會被清楚,比如執行完函式。什麼是預解析 就是在瀏覽器解析 之前,把變數的宣告和函式的宣告提公升到該作用域的最上面 什麼是變數提公升 變數提公升就是在進入乙個執行上下文...
全域性作用域 函式作用域 塊級作用域的理解
作用域是任何一門程式語言中的重中之重,因為它控制著變數與引數的可見性與生命週期。很慚愧,我今天才深入理解js的作用域.我不配做乙個程式設計師.開玩笑,什麼時候理解都不晚,重要的是理解了以後能不能深深地扎在記憶裡,不能,那就寫下來在乙個 塊 括在一對花括號中的一組語句 中定義的所有變數在 塊的外部是不...
關於作用域的理解
由花括號括起來的整體作為乙個塊,塊中的變數都具有塊作用域,僅僅在塊中可見。函式的形式參量雖然在左花括號之前,但仍具有塊作用域,塊作用域的可見範圍是從定義出開始到塊。宣告在內層塊的變數,其作用域僅僅侷限於該宣告所在的塊。double blocky double cleo q 作用域結束 return ...