javascript中闭包的真正作用

参考阮一峰的文章:http://javascript.ruanyifeng.com/grammar/function.html#toc23

1. 读取函数内部变量,封装一些私有属性

function Person(name) {
  var _age;
  function setAge(n) {
    _age = n;
  }
  function getAge() {
    return _age;
  }

  return {
    name: name,
    getAge: getAge,
    setAge: setAge
  };
}

var p1 = person('张三');
p1.setAge(25);
p1.getAge() // 25

2. 读取函数变量,使得这些变量常驻内存中

function createIncrementor(start) {
  return function () {
    return start++;
  };
}

var inc = createIncrementor(5);

inc() // 5
inc() // 6
inc() // 7
原文地址:https://www.cnblogs.com/linux-centos/p/5568602.html