3 回答

TA貢獻1777條經驗 獲得超10個贊
這是由于所謂的“吊裝”。
基本上,當您使用 時,JavaScript 會將函數移動到作用域的頂部,以便您可以在初始化之前訪問它。使用 let 不會這樣做。function
func_1();
function func_1() {
console.log("Thing");
}
func_2(); // will cause an error
let func_2 = () => console.log("Thing");
細節:從技術上講,一切都是吊裝的,但是在你到達他們的生產線之前不要初始化。如果使用 ,則該變量的開頭為letconstvarundefined
console.log(aa); //undefined
var aa = "hello";
console.log(aa); //hello
console.log(bb) // error
let bb = "hello";
旁注(這部分不是上述問題的解決方案):1.你應該使用而不是,因為我不認為你需要改變函數的值。2.這些聲明之間的另一個區別是關鍵字的值(在這種情況下是相同的,但可以不同)。我不會在這里解釋它,如果你做更多的Javascript,你可能會遇到它,所以值得研究。constletthis

TA貢獻1898條經驗 獲得超8個贊
let pickColor = ...行為類似于普通的變量聲明 + 賦值。
僅當執行實際的代碼行時,才會完成賦值。=
僅當調用發生在聲明之后且在可見范圍內時,才能調用以這種方式定義的函數。
相反,定義是完全“吊起”的,這意味著它們的行為就像在JS塊的頂部定義一樣,并且可以被稱為“在”它們的定義之前。function()
示例靈感來自 http://adripofjavascript.com/blog/drips/variable-and-function-hoisting.html:
isItHoisted();
function isItHoisted() {
console.log("Yes! This function declaration acts the same as if it was declared _before_ the call.");
}
isThisOtherOneHoisted(); // throws an ReferenceError if used before it is assigned
let isThisOtherOneHoisted = () => console.log("Javascript sees that the name exists, but the assignment has not been done.");
/**
like :
There is this variable isThisOtherOneHoisted defined later, just so you know.
isThisOtherOneHoisted(); // error, variable does not even containt a function yet
isThisOtherOneHoisted = () => console.log(...)
*/
作為其他細節,javascript仍然“看到”它在初始化之前被使用,所以這就是為什么錯誤消息與你使用根本不存在的變量不同。
對于任何變量,僅針對變量存在的事實,都會提升聲明。的賦值僅在寫入的位置執行。=

TA貢獻1911條經驗 獲得超7個贊
函數聲明
function pickColor(){...}
與使用 聲明的任何變量一起移動到作用域的頂部(首先提升)。var
其中,僅當解釋器遇到該行代碼時,才會訪問聲明的 as 函數表達式。let
示例 -
let two = () => {
console.log('something else');
}
var x = 'demo'
let y = 'demo123'
function one() {
console.log('something');
};
function three(){
one();
}
變量 , 將一旦執行開始,就會移動到作用域的頂部,xfunction one(){...}function three(){...}
x,直到為該行分配值 。undefinedx = 'demo'x'demo'
變量未啟動或分配任何值,直到行y
let y = 'demo123'
因為 用于啟動變量,因此使用 啟動的函數表達式也是如此。letlet
添加回答
舉報