I was reading some of Facebook’s JavaScript, and came across a curious function that I couldn’t figure out the purpose of:
function bagof(a) {
return function () {
return a;
};
}
As far as I can tell:
bagofis a function that accepts the parametera.bagofimmediately returns an anonymous function.- The returned function then returns the original parameter
a.
I would assume that the usage of bagof would be something like this:
newFunction = bagof("This is the data");
console.log( newFunction() ); //Logs "This is the data"
What’s the point? Why not directly use or store whatever variable or function that was passed into a?
The source file looks like it contains many utility functions for the application.
The
bagof()method can be used as a factory creating constant functions (functions always returning the same value).Even if you use in such a context:
Invocation of
randomFun()will always return the same value becauseMath.random()is evaluated only once (eagerly). I guess it is utility method used when some API requires a method and we simply want to pass constant value. Instead of:you can simply say: