iT邦幫忙

DAY 10
1

JavaScript學習路系列 第 10

JavaScript學習路-(10)Function-2

function 除了上一篇提到的函數宣告式寫法

function identifier (Arguments) {
statements...

return theValue;
}

以外,還有不同的寫法:

我叫做具名函式具名表現式:寫法是定義變數為一個有名字的函式

var hello = function identifier(Arguments) {
return Arguments;
}

我叫做匿名函式函式表現式:特點是沒有函式名字

var hello = function (Arguments) {
return Arguments;
}

這兩個式子讓函式變成變數,一樣可以用!

這裏插播一下函式的特性叫做 Function hoisting,雖然不知道要翻成什麼名詞,總之就是背起來...
codecademy 教學頁寫到:
「The two ways of declaring functions produce different results. Declaring a function one way "hoists" it to the top of the call, and makes it available before it's actually defined.」
大概意思就是函式會被吊到最上面,依照程式從第一行開始跑的特性,就算函式沒有寫在第一行依然可以宣告,但僅限於函數宣告式

所以宣告函數可以這樣用:

helloA();
function helloA () {
alert("It`s a function A!");
}

但如果想宣告具名函式或匿名函式的話這樣寫就叭叭~出現錯誤: Uncaught TypeError: undefined is not a function

helloB();
helloC();

var helloB = function helloB() {
alert("It`s a function B!");
}
var helloC = function () {
alert("It`s a function C!");
}

換個順序就可以正常運作:

var helloB = function helloB() {
alert("It`s a function B!");
}
var helloC = function () {
alert("It`s a function C!");
}
helloB();
helloC();

參考出處:
Javascript 開發學習心得 - 函數的多種寫法與應用限制
JavaScript Glossary

本文同步發表於 http://azzurro.blog.aznc.cc/learn_javascript_10/


上一篇
JavaScript學習路-(09)Function-1
下一篇
JavaScript學習路-(11)Function-3
系列文
JavaScript學習路30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

2 則留言

0
roger03
iT邦新手 4 級 ‧ 2014-09-28 21:41:11

有實用

0
tpodomoto
iT邦新手 4 級 ‧ 2014-09-29 23:57:51

謝謝!

我要留言

立即登入留言