简体   繁体   English

使用内部函数的优势(javascript)

[英]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.

相关问题 有没有一种方法可以利用在JavaScript工厂函数中使用原型方法的性能优势? - Is there a way to exploit the performance advantages of using prototype methods in JavaScript factory functions? 在 javascript 中使用柯里化函数优于普通 function 的优势 - Advantages of using curried functions over a normal function in javascript 在函数中使用参数的好处是什么? - What are the advantages of using arguments in functions? JavaScript内部函数和“此” - JavaScript Inner Functions & 'this' 在javascript中访问内部函数 - Accessing inner functions in javascript 在 Javascript 函数中使用新的 ES2015 其余参数而不是使用数组参数有什么优点? - What are the advantages of using the new ES2015 rest parameters in Javascript functions instead of using an array argument? 如何在JavaScript中使用嵌套函数作为生成器(使用“内部”收益) - How to use nested functions as generator in javascript (using “inner” yields) JavaScript内部功能和性能 - JavaScript inner-functions and Performance JavaScript和内部函数的块作用域 - Block scoping in JavaScript and inner functions 是否可以在JavaScript中使用内部函数? - Is it possible to use inner functions in JavaScript?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM