iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 2
0
自我挑戰組

JavaScript基礎30天系列 第 2

函式(function)基礎介紹 Day02

function介紹
什麼是function??
為什麼我們一定需要function呢??/images/emoticon/emoticon07.gif

這裡我們舉一個例子
https://ithelp.ithome.com.tw/upload/images/20200917/201230398zRwPg9GBk.jpg

當我們每次要計算 蛋糕與可樂數量的總價錢時
便可以使用此function
也就代表當一件事 重複性質很高(Ex:新增,修改,刪除)
就可以寫成function


function寫法

https://ithelp.ithome.com.tw/upload/images/20200917/20123039F69c6CsO2z.jpg
當撰寫function時
必須先 宣告函式
定義函式名稱
最後 要記得執行它


function帶入參數
https://ithelp.ithome.com.tw/upload/images/20200917/201230392H4aILyJGi.jpg
10 10 分別帶入cakeNum 與 cokeNum 兩個參數


全域與區域變數

這裡我們先舉個例子
https://ithelp.ithome.com.tw/upload/images/20200917/20123039bM3IJAvZBM.jpg

會發現 console.log(total) 的結果會是
https://ithelp.ithome.com.tw/upload/images/20200917/201230391NQ73gigXL.jpg
這是為什麼呢??

這就是全域與區域變數的差別
當我們在function宣告total這個變數的時候
當function執行完
此變數的記憶體會被回收
導致在外層 console.log(total)的結果
會是 is not defined

而當我們在外層先宣告total個變數
https://ithelp.ithome.com.tw/upload/images/20200917/20123039kAnZ40fEaf.jpg
console.log(total)會正確取得值

https://ithelp.ithome.com.tw/upload/images/20200917/2012303995lZ6LVcbP.jpg

不過這裡要注意
當我們使用全域變數來宣告變數的時候
我們在Chorme的console 輸入window
可以找到我們剛剛所宣告的全域變數(total)
這也就代表
假如全域變數越多
所佔的記憶體就越肥 /images/emoticon/emoticon46.gif


hoisting

  1. 函式的 Hoisting :

在JS中
會把宣告的變數移到最前面先執行
也就是
變數在宣告期間就會先建立一個記憶體空間,
等到實際運行時再將值放入到該記憶體空間內

https://ithelp.ithome.com.tw/upload/images/20200917/201230391TjM3JAZPd.jpg
結果會是
https://ithelp.ithome.com.tw/upload/images/20200917/201230398mmpsWBYxa.jpg

過程如下:
https://ithelp.ithome.com.tw/upload/images/20200917/20123039UZYuN8Fi0h.jpg

  1. 函式的 Hoisting :
    https://ithelp.ithome.com.tw/upload/images/20200917/20123039vPLCb4yR1q.jpg

結果會是

https://ithelp.ithome.com.tw/upload/images/20200917/2012303942regHiYgF.jpg
這是為什麼呢??

因為 當載入JS
函式會被放在最上面
也就是
https://ithelp.ithome.com.tw/upload/images/20200917/20123039DiCc44T77m.jpg

今天的函式介紹就告一段落
明天請繼續關注囉!!/images/emoticon/emoticon37.gif


上一篇
變數介紹 Day01
下一篇
陣列與物件 Day03
系列文
JavaScript基礎30天30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言