> For the complete documentation index, see [llms.txt](https://ayugioh2003.gitbook.io/front2end/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://ayugioh2003.gitbook.io/front2end/front/li-ji-han-shi.md).

# 立即函式

在 2016 年的某天，因為想試看看臉書的引文功能，就花了一些時間在看他們的 SDK 在幹麻。以下是其中一段

```javascript
var newHTML2 = document.createElement('div');
// newHTML2.innerHTML='<div class="fb-quote">second</div>';
newHTML2.setAttribute("id","fb-root");
document.body.appendChild(newHTML2);

(function(d, s, id) {
  var js, fjs = d.getElementsByTagName(s)[0];
  if (d.getElementById(id)) return;
  js = d.createElement(s);
  js.id = id;
  js.src = "//connect.facebook.net/zh_TW/sdk.js#xfbml=1&version=v2.6";
  fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
```

那時候我就在想:

```javascript
(function d, s, id){
 // code 
}(document, 'script', 'facebook-jssdk'))
```

這段到底在寫什麼? 我怎麼都看不懂? 後來無意間才發現這個寫法叫做「立即函式」。

## 立即函式是什麼

立即函式就是一種能夠「現在，馬上，立刻!」執行的函式。有幾種狀況會使用到它:

* 只會用到一次
* 不想要其他環境變數影響到該函式

立即函式有兩種寫法，差別只是括號放在最後、或是傳入參數的前面而已

```javascript
// 第一種
(function(arg){// 程式碼}(in));
// 第二種
(function(arg){// 程式碼})(in);
```

那為什麼立即函式長的這麼奇怪呢? 有文章說([Re: \[問題\] (...)()或 (...)(window) 是什麼意思? - ptt](https://www.ptt.cc/bbs/Ajax/M.1342196893.A.421.html))，他是由兩種語法組成的: 函式呼叫和實字。

* [Re: \[問題\] (...)()或 (...)(window) 是什麼意思? - 看板 Ajax - 批踢踢實業坊](https://www.ptt.cc/bbs/Ajax/M.1342196893.A.421.html)
* [Javascript 開發學習心得 - 函數的多種寫法與應用限制 @ 小雕雕的家 :: 痞客邦 PIXNET ::](http://sweeteason.pixnet.net/blog/post/40371736-javascript-%E9%96%8B%E7%99%BC%E5%AD%B8%E7%BF%92%E5%BF%83%E5%BE%97---%E5%87%BD%E6%95%B8%E7%9A%84%E5%A4%9A%E7%A8%AE%E5%AF%AB%E6%B3%95%E8%88%87%E6%87%89)

### 函式呼叫

函式就是用變數 or 函數名，將一段語法包起來。之後呼叫變數名 or 函數名叫能使用這段語法。函式呼叫有三種寫法:

第一種是具名函式，他的函式是有名字的。例如本例的函式名字叫做 `add()`

```javascript
//具名函數
var addfun = function add(a,b) {
   return a + b;
}
```

第二種是匿名函式，只能透過 `addfun` 這個變數來呼叫

```javascript
//匿名函式
var addfun = function (a,b) {
   return a + b;
}
```

第三種是函式宣告式，function 也有名字

```javascript
//函數宣告式
function add(a,b) {
  return a + b;
}
```

* [Javascript 開發學習心得 - 函數的多種寫法與應用限制 @ 小雕雕的家 :: 痞客邦 PIXNET ::](http://sweeteason.pixnet.net/blog/post/40371736-javascript-%E9%96%8B%E7%99%BC%E5%AD%B8%E7%BF%92%E5%BF%83%E5%BE%97---%E5%87%BD%E6%95%B8%E7%9A%84%E5%A4%9A%E7%A8%AE%E5%AF%AB%E6%B3%95%E8%88%87%E6%87%89)

### 實字 literal

實字是產生物件的一種方式。JS 產生物件(實例)有兩種方式: 建構式和實字，例如 json 格式就是一種實字。

```javascript
// 實字
var obj1 = { name : "總裁實字",
             height : 170,
             say : function(){
               return "I am " + obj1.name;
              }
            },
result = obj1.say();


// 建構式
// js 沒有 class 概念，要用函式模擬
function Person(name){

  // var this = {};
  this.name = name;
  this.say = function(){
    return "I am " + this.name;
  };

  // return this;

};

var adam = new Person("海綿寶寶");
console.log(adam.say());
```

```markup
<h1>
  <p id="demo> paragraph </p>
</h1>
```

* [JavaScript 教學 88：設計模式（實字與建構式） - iT 邦幫忙:: 一起幫忙解決難題，拯救 IT 人的一天](http://ithelp.ithome.com.tw/articles/10118805)
* [JavaScript 教學 89：設計模式（實字與建構式～續） - YouTube](https://www.youtube.com/watch?v=peAoPF6rM00)
* [Function 實例](http://openhome.cc/Gossip/JavaScript/FunctionInstance.html)
* [Javascript 開發學習心得 - 物件實字與建構式 + Callback @ 小雕雕的家 :: 痞客邦 PIXNET ::](http://sweeteason.pixnet.net/blog/post/40359127-javascript-%E9%96%8B%E7%99%BC%E5%AD%B8%E7%BF%92%E5%BF%83%E5%BE%97---%E7%89%A9%E4%BB%B6%E5%AF%A6%E5%AD%97%E8%88%87%E5%BB%BA%E6%A7%8B%E5%BC%8F-%2B-c)

## 相關連結

* [VITO の 學習筆記: 函式](http://vito-note.blogspot.tw/2014/08/blog-post_10.html?m=1)
* [iT 邦幫忙:: 一起幫忙解決難題，拯救 IT 人的一天](http://ithelp.ithome.com.tw/m/articles/10127299)
* [6.6 立即函式 · 從 HTML 入門至實務應用](https://l7960261.gitbooks.io/html-css-javascript/content/section6-6.html)
* [JavaScript 中的函數：閉包，this，高階函數 - 壹讀](https://read01.com/0dBm.html)
* [Closure 閉包 - eddychang.me](http://eddychang.me/blog/javascript/84-js-clousure.html)
* [深入淺出 JavaScript Lambda](http://www.jollen.org/blog/2013/10/javascript-lambda.html)
* [深入理解 JavaScript 系列（4）：立即調用的函數表達式 - 湯姆大叔 - 博客園](http://www.cnblogs.com/TomXu/archive/2011/12/31/2289423.html)
* [Re: \[問題\] (...)()或 (...)(window) 是什麼意思? - 看板 Ajax - 批踢踢實業坊](https://www.ptt.cc/bbs/Ajax/M.1342196893.A.421.html)
* [Javascript 開發學習心得 - 函數的多種寫法與應用限制 @ 小雕雕的家 :: 痞客邦 PIXNET ::](http://sweeteason.pixnet.net/blog/post/40371736-javascript-%E9%96%8B%E7%99%BC%E5%AD%B8%E7%BF%92%E5%BF%83%E5%BE%97---%E5%87%BD%E6%95%B8%E7%9A%84%E5%A4%9A%E7%A8%AE%E5%AF%AB%E6%B3%95%E8%88%87%E6%87%89)
* [Javascript 開發學習心得 - 物件實字與建構式 + Callback @ 小雕雕的家 :: 痞客邦 PIXNET ::](http://sweeteason.pixnet.net/blog/post/40359127-javascript-%E9%96%8B%E7%99%BC%E5%AD%B8%E7%BF%92%E5%BF%83%E5%BE%97---%E7%89%A9%E4%BB%B6%E5%AF%A6%E5%AD%97%E8%88%87%E5%BB%BA%E6%A7%8B%E5%BC%8F-%2b-c)


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://ayugioh2003.gitbook.io/front2end/front/li-ji-han-shi.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
