JSFiddle - React, Tailwind, and code Playground
by pettys
JavaScript
// closure demo
function getAlertFunction(message) {
return function() {
alert(message);
};
// note: local variable "message" goes out of
// scope here, but the returned function will
// need it when it's invoked. JavaScript
// attaches this to the function instance.
// This "attachment" makes it a closure variable.
}
var hi = getAlertFunction("hi");
var there = getAlertFunction("there");
// At this point, both hi and there refer to functions
// with the exact same source code. But each instance of
// the function has its own closure variable context.
hi();
there();
// C# has the same concept; closure is implemented as
// a compiler trick. When you create a lambda expression
// that references variables in the parent scope, the
// compiler creates an object that holds these variables
// makes them available to the lambda function.
//
// int id = 4;
// list.Where(item => item.itemId == id);
//
// id is a closure variable; reverse-compiling this shows
// the "hidden" object that encapsulates the closure state.