4-43 White space

4-44 Immediately invoked function expressions(IIFEs)

function 被宣告後馬上被執行,回傳hello字串給greeting

IIFEs
1
2
3
4
5

var greeting = function (name){
return ('Hello ' + name);
}('Necisam');
//greeting hold the string returned by function

syntax parse saw function keyword in the starting in a line, it expects that this is a function statement

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

3;// an expression

// an expressions
{
name : "necisam",
country : "Taiwan"
}

// expressions
function (name){
return "Hello " + name;
}

//to trick syntax parser, make it become an expression
//parenthesis is a operator in JS
(function (name){
return "Hello " + name;
});

//invoke a function expression !!
(function (name){
return "Hello " + name;
}('Necisam'));

4-45 IIFEs and safe code

因為是呼叫function,有自己的 execution context
所有function 不會動到 global
如果真的需要global的內容,下面給了一個範例
能夠安全的access global content

1
2
3
4
5
6
7
8
9
10
11

var greeting = 'Hola';

// objects are passed by reference
(function (global, name){
var greeting = 'Hello';
global.greeting = 'Hello';
console.log(greeting + ' ' + name);
}(window, 'Necisam'));

console.log(greeting);//Hello, modfied by function