Personal understanding closure: function defined inside a function, a function of outsourcing internal functions can access variables defined.
Features closure: Variable resident memory
demo implement a similar function call Counter:
function Fn () { var C = 0 ; function Inner () { C + =. 1 ; the console.log (C) } return Inner; } var F1 = Fn (); F1 (); // . 1 F1 (); / / 2 C is not released, the memory resident
Use Scenario 1: setTimeout reference function to pass parameters (only the first parameter is a reference setTimeout function)
function laterCall(a){ return function(){ console.log("a:",a) } } var fn2 = laterCall(123); setTimeout(fn2,1000)
Use Scenario 2: Analog private member
var module1 = (function(){ var a = 1; var addOne = function(){ a += 1; return a }; var subOne = function(){ a -= 1; return a }; return{ addOne:addOne, subOne:subOne } })(); module1.addOne() module1.subOne()
Use Scenario 3: object-oriented
function User(name){ this.say = function(){ console.log("hello "+ name); } } var user = new User("frank"); user.say();