> For the complete documentation index, see [llms.txt](https://mistborn.gitbook.io/til-coding/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://mistborn.gitbook.io/til-coding/javascript/the-new-function-syntax.md).

# The "new Function" syntax

## Syntax

```javascript
let func = new Function ([arg1, arg2, ...argN], functionBody);

// 有參數
let sum = new Function('a', 'b', 'return a + b');
alert( sum(1, 2) ); // 3

// 無參數
let sayHi = new Function('alert("Hello")');
sayHi(); // Hello

// 最大的不同是用字串建構一個函式，使用的廠景很特殊，像是從 server 取得函式程式碼。
let str = ... receive the code from a server dynamically ...
let func = new Function(str);
func();
```

## Closure

```javascript
// new 創建的函式 [[Environment]] 指向全域，因此得不到函式內部的變數。
function getFunc() {
  let value = "test";

  let func = new Function('alert(value)');

  return func;
}

getFunc()(); // error: value is not defined

// normal
function getFunc() {
  let value = "test";

  let func = function() { alert(value); };

  return func;
}

getFunc()(); // "test", from the Lexical Environment of getFunc

// 這樣的特性可以減少使用上的錯誤，假設寫腳本時不知道 new 函式的程式碼，執行時才能獲得程式碼，
// 我們可能會用 minifier 打包，這樣函式內部變數會被改變，當 new 的程式碼被傳進來時，已經
// 不知道他的變數是哪個內部變數了。
```
