JSFiddle - React, Tailwind, and code Playground
by shengoo
JavaScript
function makeCounter() {
// 只能在makeCounter内部访问i
var i = 0;
return function () {
console.log(++i);
};
}
// 注意,counter和counter2是不同的实例,分别有自己范围内的i。
var counter = makeCounter();
counter(); // logs: 1
counter(); // logs: 2
var counter2 = makeCounter();
counter2(); // logs: 1
counter2(); // logs: 2
//alert(i); // 引用错误:i没有defined(因为i是存在于makeCounter内部)。