4-46 Understanding Closures

  • why whattosay is still exist when invoking sayHi ?

  • greet function is pop off the execution stack, so whattosay should be clear.

  • Closures: closing in all variables that the function supposed to have access to

  • the execution context has closed in its outer environment reference(only variables, not values), even though those outer execution contexts are gone.

1
2
3
4
5
6
7
8
9

function greet(whattosay){
return function(name){
console.log(whattosay + ', ' + name);
}
}
greet('Hey')('Necisam');//Hey, Necisam
var sayHi = greet('Hey');// a function
sayHi('Necisam');

4-47 Understanding Closures part2

Closures close only the variables, not the values.

  • Free variables : it is outside a function, but that you have access to.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

function buildFunctions(){
var arr = [];
for(var i = 0; i < 3; i++){
arr.push(
function(){
console.log(i);
}
);
}
return arr;
}
var fs = buildFunctions();
fs[0]();
fs[1]();
fs[2]();
// 3 3 3
// i is set to 3 after the loop
//

to execute the functions to get different execution context that contains different J s.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function buildFunctions(){
var arr = [];
for(var i = 0; i < 3; i++){
arr.push(
(function(j){
return console.log(j);
}(i))
);
}
return arr;
}
var fs = buildFunctions();
fs[0]();
fs[1]();
fs[2]();

ES6 solution

  • let allows you to declare variables that are limited in scope to the block, statement, or expression on which it is used.
  • each j would be a new variables in mem(just like c language)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

function buildFunctions(){
var arr = [];
for(var i = 0; i < 3; i++){
let j = i;
arr.push(
function(){
console.log(j);
}
);
}
return arr;
}
var fs = buildFunctions();
fs[0]();
fs[1]();
fs[2]();

4-48 Funciton factories

  • Every time the function be invoked, a new execution context is created.
  • This lets us create functions from other functions.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

function makeGreeting(language){
return function(firstname,lastname){
if(language === 'en'){
console.log('Hello '+ firstname + lastname);
}
if(language === 'es'){
console.log('Hola' + firstname + lastname);
}
}
}

var gEnglish = makeGreeting('en');
var gSpanish = makeGreeting('es');
gEnglish('YuCheng','Cheng');
gSpanish('YuCheng','Cheng');

4-49 Closures and Callbacks

bigword alert : Callback funcion

  • A function you give to another function, to be run when the other function is finished
1
2
3
4
5
6
7
8
9
10

function sayHiLater(){
var greeting = 'Hi!';

setTimeout(functions(){
console.log.(greeting);
}, 3000);
}

sayHiLater();