let x = 5;
function setFn() {
let x = 0;
return function() {
console.log(this)
console.log(x)
x = x + 1;
return x;
};
}
const f1 = setFn();
const f2 = setFn();
console.log(f1()); // 1
console.log(f2()); // 1
console.log(f1()); // 2
console.log(f2()); // 2
词法环境在代码写完后其实就确定了,和this不一样,setFn中返回的函数中调用的x是setFn中的,而不是外部的x。
每次setFn调用都会产品一个新的x,所以f1和f2中使用的x不是同一个