Re: [問題] Hoisting 問題

看板Ajax作者 (Have Fun)時間7年前 (2017/02/19 03:32), 編輯推噓6(608)
留言14則, 7人參與, 最新討論串2/3 (看更多)
※ 引述《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 就是逐行的去執行程式碼 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 61.231.184.212 ※ 文章網址: https://www.ptt.cc/bbs/Ajax/M.1487446363.A.C17.html

02/19 08:52, , 1F
這個解釋才是正確的
02/19 08:52, 1F

02/19 10:04, , 3F
g/我是看這篇的,請問他的觀念正確嗎?
02/19 10:04, 3F

02/19 10:58, , 4F
以前還滿多人這樣理解的,但 ES6 後有 const, let 就不能
02/19 10:58, 4F

02/19 10:58, , 5F
這樣解釋
02/19 10:58, 5F

02/19 18:48, , 6F
const 和 let 不會提升
02/19 18:48, 6F

02/19 19:00, , 7F
感謝大大指正,晚點小弟把他補充進blog
02/19 19:00, 7F

02/19 20:07, , 8F
背後的原理是2 phase執行,Hoist是轉換成等效且可以1 phase
02/19 20:07, 8F

02/19 20:07, , 9F
(適合一般人讀程式碼流程)執行的樣子,不是說js engine真的
02/19 20:07, 9F

02/19 20:07, , 10F
會這樣搬
02/19 20:07, 10F

02/19 20:54, , 11F
const和let一樣會在creation phase就產生,只是要到assign
02/19 20:54, 11F

02/19 20:55, , 12F
的那行過了之後才給用
02/19 20:55, 12F

02/19 20:58, , 13F
沒有hoist是這個規則下的結果
02/19 20:58, 13F

04/09 15:17, , 14F
感謝推文解釋
04/09 15:17, 14F
文章代碼(AID): #1OgA5RmN (Ajax)
討論串 (同標題文章)
文章代碼(AID): #1OgA5RmN (Ajax)