JavaScript的這種行爲被稱爲提升。對MDN有很好的解釋(https://developer.mozilla.org/en-US/docs/Glossary/Hoisting)
在JavaScript中,函數和變量被掛起。提升是JavaScript將聲明移動到作用域頂部(全局作用域或當前函數作用域)的行爲。
這意味着您可以在聲明它之前使用函數或變量,換句話說:函數或變量可以在已被使用之後聲明。
基本上,如果聲明這樣一個變量:
console.log(s); // s === undefined
var s = 'some string';
s
聲明將是「懸掛」到範圍的開始(即,會出現線路上無ReferenceError
與console.log
)。 變量的值不會在那一刻被定義,雖然。
這同樣與分配一個匿名函數的變量,所以:
console.log(f); // f === undefined
f(); // TypeError: f is not a function
var f = function() {}; // assigning an anonymous function as a value
f(); // ok, now it is a function ;)
變量將被吊起,從而在整個範圍內可見,但它的價值,即使它是一個函數,將仍然未定義 - 因此如果您嘗試執行該錯誤。
在另一方面,如果你定義一個名爲功能:
console.log(f); // f === function f()
f(); // we can already run it
function f() {}; // named function declaration
它的定義也將懸掛,所以你甚至可以在你已經宣佈它的範圍的第一行運行它。
[Javascript函數範圍和提升]的可能重複(http://stackoverflow.com/questions/7506844/javascript-function-scoping-and-hoisting) – DTing
是的。在輸入[*執行上下文*](http://ecma-international.org/ecma-262/6.0/index.html#sec-execution-contexts)時,所有函數和變量聲明都將在任何代碼運行之前處理。 – RobG