Closure
閉包可以保存函式內的變數,無法存函式外改變變數的值,並應用到巢狀函式內。
A couple of questions
// 函式使用外部變數,會使用最新的值嗎?
let name = "John";
function sayHi() {
alert("Hi, " + name);
}
name = "Pete";
sayHi(); // what will it show: "John" or "Pete"?
// 函式會使用內部變數還是外部變數?
function makeWorker() {
let name = "Pete";
return function() {
alert(name);
};
}
let name = "John";
// create a function
let work = makeWorker();
// call it
work(); // what will it show? "Pete" (name where created) or "John" (name where called)?Lexical Environment


Function Declaration

Inner and outer Lexical Environment


Nested functions

Environments in detail







Code blocks and loops, IIFE
if

for
Code blocks
IIFE
Garbage collection
Real-life optimizations
Last updated