作者kisha024 (4545454554)
看板Ajax
標題[問題] javascript 函數的提升
時間Thu May 12 16:09:57 2016
各位好
我是參考這裡的資料
http://fireqqtw.logdown.com/posts/258823-javascript-function-notes
function one() {
console.log('global one');
}
function two() {
console.log('global two');
}
function hoistFun() {
console.log(typeof one);
console.log(typeof two);
one();
two();
function one() {
console.log('local one');
}
var two = function() {
console.log('local two');
}
}
---------------------------------------------------------------------
我不懂的是 two這個函數不是在hoistFun()裡面又被定義一次
為什麼console.log(typeof two); 結果卻是undefined?
另一個問題是 底下這兩種宣告方式 在使用上都是寫 two();
那到底有什麼差別呢? 謝謝
function two() {
console.log('global two');
}
var two = function() {
console.log('local two');
}
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 140.127.81.14
※ 文章網址: https://www.ptt.cc/bbs/Ajax/M.1463040600.A.5A7.html
推 Kenqr: 變數宣告會自動移到函數的開頭,所以two等於是在hoistFun 05/12 16:50
→ Kenqr: 的開頭就宣告了,但是在console.log之後才定義內容, 05/12 16:50
→ Kenqr: 所以console.log時會顯示為undefined 05/12 16:50
→ johnny9144: 可以看一下 JavaScript 的優良部份 有討論這個問題 05/12 20:00
推 mrbigmouth: 大推優良部份 很多讓人confuse的js問題這裡都講了 05/12 20:02
→ kisha024: 謝謝 05/13 15:31