※ 引述《broo (陳爺)》之銘言:
: 標題: [問題] Hoisting 問題
: 時間: Sat Feb 18 23:48:05 2017
: 範例是這樣的
: (function(){
: var test =function(){return 1;}
: function test() {return 2;}
: return test();
: })();
: 經過hoistibg後會長這樣
: (function(){
: var test;
: function test() {return 2;}
: test = function() {return 1;}
: return test();
: })();
: 我怎麼想結果都是2,因為最後是return test()不是嗎??為什麼會是1呢
: 腦筋無法轉過來..
: 麻煩了 手機排版請見諒
我覺得hoisting應該不是這樣解釋
https://developer.mozilla.org/zh-TW/docs/Glossary/Hoisting
hoisting teaches that variable and function declarations are physically moved
to the top your coding, but this is not what happens at all. What does happen
is the variable and function declarations are put into memory during the
compile phase, but stays exactly where you typed it in your coding.
簡單講就是javascript會分creation跟execution phases
會先執行creation phases
把宣告的變數跟宣告的function存到記憶體
(此時變數還沒被assign,所以value會是undefined)
然後再執行excution phases
就是逐行的去執行程式碼