Languages which support closure (such as JavaScript, Swift, and Ruby) will allow you to keep a reference to a scope (including its parent scopes), even after the block in which those variables were declared has finished executing, provided you keep a reference to that block or function somewhere.
outer = function() {
var a = 1;
var inner = function() {
console.log(a);
}
return inner; // this returns a function
}
var fnc = outer(); // execute outer to get inner
fnc();
As you might be able to guess, when I callfnc()
it prints the value ofa
, which is "1".
===========================
function add (a) { return function (b) { return a + b; } } var add3 = add(3); add3(4); // returns 7
========================
var add = (function () {
var counter = 0;
return function () {counter += 1; return counter}
})();
add();
add();
add();
// the counter is now 3
Comments
Post a Comment