user3711105 user3711105 - 1 month ago 5
Javascript Question

Bind a changing variable in function, I want a name

I have somethings like:

var i = 0;

var func = function(){
console.log(i);
};

func(); //0

i++;

func(); //1


I want to have the second console also output '0',
so I change the program like:

var i = 0;

var func = (function(_i){
return function(){
console.log(_i);
};
})(i);

func(); //0

i++;

func(); //0


I know how it works, but is there any name or terms to describe such mechanism?

Answer

It's called a closure. You can read more about them here:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures

Comments