Advertisement
Guest User

Untitled

a guest
Jun 26th, 2017
42
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.90 KB | None | 0 0
  1. function greet(whattosay) {
  2. return function(name) {
  3. console.log(whattosay + ' ' + name);
  4. }
  5. }
  6.  
  7. greet('Hi')('navi'); // Hi navi (as expected)
  8.  
  9. var sayHi = greet('Hi');
  10. sayHi('Tony');
  11. // Above statement prints Hi Tony, even if function greet has finished its execution so its argument value of whattosay should not exist, because value of whattosay 'Hi' is stored in closure, because it is used in inner function.
  12.  
  13.  
  14. function buildFunctions() {
  15. var arr = [];
  16. for (var i = 0; i < 3; i++) {
  17. arr.push(
  18. function () {
  19. console.log(i);
  20. // this function is not being called here, its definition is being pushed
  21. // the variable i is pushed not the value of i
  22. }
  23. );
  24. }
  25. return arr;
  26. }
  27.  
  28. var fs = buildFunctions();
  29.  
  30. fs[0](); // 3
  31. fs[1](); // 3
  32. fs[2](); // 3
  33.  
  34. // All of above when called retrieves the value of i from the closue which was 3 when outer function completed its execution.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement