--- type: slide --- # 立即執行函式(IIFE) ###### tags:`HyUI4.0` --- 指的是可以立即執行的Functions Expressions函式表示式,中文多譯為立即(執行)函式。 --- 一般寫 function 會這樣寫 ```javascript= [1-3|4|6-8|9 ] function hello(name) { return `hello ${name}`; } console.log(hello2('jack')); // hello jack ``` --- 立即執行可以這樣做,function 用()包起來之後結尾在加(),這樣可以馬上執行該函式 ```javascript= [1-3|5-7|8] (function (name) { console.log(`hello ${name}`); // hello jack })('jack'); ``` --- 另外使用立即函示也可以具名 ```javascript= (function hello(name) { console.log('hi!') })(); ``` 但是無法另外調用 ```javascript= hello() // hello is not defined ``` --- 因為作用域的關係,立即函示裡面的變數不會影響到全域或是其他作用域的資料 ```javascript= [1|2-5|6] var name = '小明'; (function(){ var name = '小華'; console.log(name); // 小華 })(); console.log(name); // 小明 ``` --- 立即函式也可以傳參數,可以回傳值,並以變數接收回傳值。 下面的範例是將一個立即函式的執行結果傳遞給另一個立即函式 ```javascript= [2-4|6-8|10] var obj = {}; (function (a) { a.person = '小明'; })(obj); (function (b) { console.log(b.person); // 小明 })(obj); console.log(obj); // {person:小明} ``` --- 參考資料 [Day20 立即呼叫的函式表示式(IIFE)](https://ithelp.ithome.com.tw/articles/10193313) [JavaScript 核心篇 學習筆記: Chap.43–立即函式](https://medium.com/@yining1204/javascript-%E6%A0%B8%E5%BF%83%E7%AF%87-%E5%AD%B8%E7%BF%92%E7%AD%86%E8%A8%98-chap-43-%E7%AB%8B%E5%8D%B3%E5%87%BD%E5%BC%8F-c30454f3abff) <style> .reveal h1{ font-size:2em; } .reveal h1,.reveal h2 { color:#c9f2ff; } </style>
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up