克服JS奇怪的部分_立即呼叫式(IIFEs)與安全程式碼

Huang Pei
4 min readSep 19, 2019

立即呼叫函式(IIFEs)

本筆記出自:JavaScript 全攻略:克服 JS 的奇怪部分

立即函式 (IIFE )

定義完馬上就執行的函式。

  1. 是使用Grouping Operator () 包起來的匿名函式。這樣的寫法可以避免裡面的變數污染到 global scope。
  2. 馬上執行 function 的 expression (),JavaScript 引擎看到它就會立刻轉譯該 function。
// function statement  function greet(name) {
console.log(‘Hello’ + name) // Hello Iris}
greet(‘Iris’)// function expression var greetFunc = function (name) {
console.log(‘Hello’ + name) // Hello Iris}
greetFunc(‘Iris’)

IIFE (Immediately Invoked Function Expression)

  var greeting = function (name) {
return ‘Hello’ + name}(‘Iris’) // 立即呼叫,回傳一字串
console.log(greeting) // Hello Iris 回傳的字串
console.log(greeting())
//string(Hello Iris) is not a function,已立即呼叫過了

IIFE轉換為 expression 形式,並且馬上執行,function scope 內的變數在外面是無法存取的(避免變數污染)

在瀏覽器中隨意輸入:數字:428; // 428 可以正常回傳數字字串:'Hello world!'; // 'Hello world!' 可以正常回傳字串物件:{ name:'Iris' }; // { name:'Iris' } 可以正常回傳物件函數  一般函式:function greeting{
return console.log('Hello' + name)}; //Undefined
匿名函式:function () {
return console.log('Hello' + name)}; //Unexpected token
*語法解析器看到function這個字在一行的最前面或是接在分號後,
它預期這是一個函數陳述句,它想要這有個名稱,函式不可以是匿名的

如果寫了function,這個匿名函式它不是個函數表示式而是函數陳述句,會發生上面的Unexpected token問題,因此,只要確保function這個字不是程式碼的第一個字母,就不會是問題了。

使用()將函式包住轉換為表達式的寫法,因為()內永遠都會是表達式:

//expression(function (name) {
return console.log(‘Hello’ + name)})(‘Iris’) // 立即呼叫

使用IIFE避免變數互相污染:

此時在IIFE內部的變數greeting不會受IIFE干擾,console.log = ‘Hola’

若想要更改IFFE外的變數,代入即可

var greeting = ‘Hola’;(function(global, name){  var greeting = ‘Hello’;
global.greeting = ‘Hello’ //讓Hola變成Hello
console.log(greeting+’’+name)
})(window, ‘Iris’) //取用全域中的變數,並代入IIFE中來更改全域變數console.log(greeting) // Hello

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Huang Pei
Huang Pei

Written by Huang Pei

記錄用倉庫,歡迎指正。菜鳥前端,最菜的那種(超能力少女です)。

No responses yet

Write a response