Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var addTo = function(passed){
- var inner=2;
- return passed+inner;
- };
- console.log(addTo(3)); // 5
- // Constant arguments can also be declared outside the function, and are accessible inside
- var passedArg=3;
- var addToNoArgs = function(){
- var innerVal=2;
- return innerVal+passedArg;
- }
- console.log(addToNoArgs()); // We get the same answer 5
- /*
- This is possible due to lexical scoping used by Js. This concept of functions being able to accesss/ store values from outer arguments
- is called closure. Although it can get more complex, this example serves as a basic understanding
- */
- console.dir(addToNoArgs);
- // Lets take a more complex example
- var addNum = function(passedArg){
- var add= function(inner){
- return inner+passedArg;
- };
- return add;
- };
- var add3 = addNum(3);
- var add4 = addNum(4);
- console.log(add3(1)); // prints 4
- console.log(add4(1)); // prints 5
- // 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