Advertisement
Guest User

Untitled

a guest
Apr 25th, 2017
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.97 KB | None | 0 0
  1. var addTo = function(passed){
  2. var inner=2;
  3. return passed+inner;
  4. };
  5.  
  6. console.log(addTo(3)); // 5
  7.  
  8. // Constant arguments can also be declared outside the function, and are accessible inside
  9. var passedArg=3;
  10. var addToNoArgs = function(){
  11. var innerVal=2;
  12. return innerVal+passedArg;
  13. }
  14. console.log(addToNoArgs()); // We get the same answer 5
  15.  
  16. /*
  17. This is possible due to lexical scoping used by Js. This concept of functions being able to accesss/ store values from outer arguments
  18. is called closure. Although it can get more complex, this example serves as a basic understanding
  19. */
  20.  
  21. console.dir(addToNoArgs);
  22.  
  23. // Lets take a more complex example
  24. var addNum = function(passedArg){
  25. var add= function(inner){
  26. return inner+passedArg;
  27. };
  28. return add;
  29. };
  30.  
  31. var add3 = addNum(3);
  32. var add4 = addNum(4);
  33. console.log(add3(1)); // prints 4
  34. console.log(add4(1)); // prints 5
  35. // Hence by using closures, addNum preserves the value passed to it, and uses it in the computation of the add method!
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement