this might not be a very specific question but I was wondering what are the advantages of using an inner function? I've recently started reading on closures (javascript) and they always refer to inner functions.
var pet = function(name) {
var getName = function() {
return name;
}
return getName;
}
myPet = pet('Vivie');
myPet();
Why would we not want to seperate the getName function and introduce a 'name' parameter so that we could call it independantly?
var pet = function(name){
return getName();
}
function getName(name){
return name;
}
Thank you, I am quite new to javascript
Try this article. Simple guide to understand closure in JavaScript
I copied here a part of the code explained in the article. Run this code snippet to see the behavior of the inner function.
<script> function outer() { var b = 10; var c = 100; function inner() { var a = 20; console.log("a= " + a + " b= " + b); a++; b++; } return inner; } var X = outer(); // outer() invoked the first time var Y = outer(); // outer() invoked the second time //end of outer() function executions X(); // X() invoked the first time X(); // X() invoked the second time X(); // X() invoked the third time Y(); // Y() invoked the first time </script>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.