. 利用创建私有变量来保护数据、隐藏数据;外部无法直接访问,只能通过内部函数访问
. 尽量少使用全局变量;避免全局变量污染环境
. 通常使用return把内部变量/临时变量,如instance,暴露出去给外部使用
const singleton = (function () { let instance; return function () { if (!instance) //创建instance return instance } })()
let a; function fa() { let tmp = 10; return function res() { return tmp; } } a = fa(); console.log(a());
function fb() { let a = 10; return function res(inc) { a += inc; return a; } } let b = fb(); console.log(b(2)); console.log(b(2));
let fn; function assign() { let tmp = 12; fn = function () { return tmp; } } assign(); console.log(fn());
let num = 0; function fn() { num++; console.log('fn() done ', num); return num; }
fn() fn() done 1 1 fn() fn() done 2 2 fn() fn() done 3 3 fn() fn() done 4 4 num=100 100 fn() fn() done 101 101
function fn() { let num = 0; return function () { num++; console.log('fn() done ', num); } } let a = fn();
a() fn() done 1 undefined a() fn() done 2 undefined num=100 100 a() fn() done 3 undefined a() fn() done 4 undefined