[英]Advantages of using inner functions(javascript)
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.
我最近开始阅读闭包(javascript),它们总是引用内部函数。
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? 为什么我们不想分离getName函数并引入一个'name'参数,以便我们可以独立地调用它?
var pet = function(name){
return getName();
}
function getName(name){
return name;
}
Thank you, I am quite new to javascript 谢谢,我对javascript很陌生
Try this article. 试试这篇文章。 Simple guide to understand closure in JavaScript
理解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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.