塊級函數(Block-Level Functions)瀏覽器
在ES3及之前,在塊內聲明一個函數會報語法錯誤,可是全部的瀏覽器都支持塊級函數。不幸的是,每一個瀏覽器在支持塊級函數方面都有一些細微的不一樣的行爲。因此開發者最好不要在塊內聲明函數。爲了解決瀏覽器在塊內支持聲明函數時帶來的兼容性問題,在ES5中能夠使用strict模式,這樣若是開發者試圖定義一個塊內函數,就會報錯:函數
"use strict"; if (true) { //throws a syntax error in ES5 function soSomething() { //... } }
在ES6中,上面的doSomething函數是一個塊級函數,而且能夠在同一塊內調用:spa
"use strict"; if (true) { console.log(typeof doSomething); // "function" function doSomething() { //... } doSomething(); } console.log(typeof doSomething); // "undefined"
上面的代碼中,doSomething被提高到塊頂部,在塊外不能被訪問到。code
決定什麼時候使用塊級函數(Deciding When to Use Block-Level Functions)blog
塊級函數與let函數表達式類似,當代碼執行出塊後,函數的定義就被移除了。二者的區別是塊級函數會被提高到塊的頂部,而let函數表達式則不會。參見下面的例子:ci
"use strict"; if (true) { console.log(typeof doSomething); // "error" let doSomething = function() { //... } doSomething(); } console.log(typeof doSomething); // "undefined"
ES6中也能夠在non-strict模式下定義塊級函數,可是跟在strict模式下會有不一樣。塊級函數會被提高到整個函數頂部或者全局環境中:作用域
if (true) { console.log(typeof doSomething); // "function" let doSomething = function() { //... } doSomething(); } console.log(typeof doSomething); // "function"
在這個例子中,doSomething函數會被提高到全局做用域中,所以上面兩處都會輸出function。開發