提升變數
了解 hoisting 將會幫助你編寫函式 scope。只要記得,變數宣告和函式定義都會被提升到頂端。變數定義則不會,即使你宣告和定義一個變數再同一行。變數宣告是讓系統知道變數的存在,而定義只是分配給它一個值。
function doTheThing() {
// ReferenceError: notDeclared 沒有被定義
console.log(notDeclared);
// 輸出:undefine
console.log(definedLater);
var definedLater;
definedLater = 'I am defined!'
// 輸出:'I am defined!'
console.log(definedLater)
// 輸出:undefined
console.log(definedSimulateneously);
var definedSimulateneously = 'I am defined!'
// 輸出:'I am defined!'
console.log(definedSimulateneously)
// 輸出:'I did it!'
doSomethingElse();
function doSomethingElse(){
console.log('I did it!');
}
// TypeError: undefined 不是一個函式
functionVar();
var functionVar = function(){
console.log('I did it!');
}
}
為了讓你的程式碼更容易閱讀,將你所有的變數宣告在你的函式 scope 頂端,這樣可以更清楚知道變數是來自哪個 scope。在你使用變數之前請先定義。在你的 scope 底部定義函式,來保持它們的方式。
MEET THE NEW JSTIPS BOOK
You no longer need 10+ years of experience to get your dream job.
Use the 100 answers in this short book to boost your confidence and skills to ace the interviews at your favorite companies like Twitter, Google and Netflix.
GET THE BOOK NOW
MEET THE NEW JSTIPS BOOK
The book to ace the JavaScript Interview.
A short book with 100 answers designed to boost your knowledge and help you ace the technical interview within a few days.
GET THE BOOK NOW