js closures
by John Wick
JavaScript
console.clear();
// https://stackoverflow.com/questions/111102/how-do-javascript-closures-work
function sayHello(name) {
var text = 'Hello ' + name;
var f1 = function() {
console.log('f1 called');
}
var say = function() {
console.log(text);
f1();
}
say();
}
sayHello('Joe');
console.log(" ");
function sayHello2(name) {
var text = 'Hello ' + name; // Local variable
var say = function() {
console.log(text);
}
return say;
}
var say2 = sayHello2('Bob');
say2(); // logs "Hello Bob"
function say667() {
// Local variable that ends up within closure
console.log("say667...");
var num = 42;
var say = function() {
console.log(num);
}
num++;
return say;
}
var sayNumber = say667();
sayNumber(); // logs 43
console.log(" ");
function sayAlice() {
console.log("sayAlice..");
var say = function() {
console.log(alice);
}
// Local variable that ends up within closure
var alice = 'Hello Alice';
return say;
}
sayAlice()();// logs "Hello Alice"
console.log(" ");
function foo(x) {
console.log("foo");
var tmp = 3;
return function (y) {
console.log("foo > anonnymouse function");
// 2 + y + (4)
console.log('x,y,tmp ',x,y,tmp)
console.log(x + y + (++tmp)); // will also log 16
}
}
var bar = foo(2); // bar is now a closure.
bar(10);