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

时间:2019-06-06 15:25:38

标签: javascript function

这可能不是一个非常具体的问题,但是我想知道使用内部函数的优点是什么?我最近开始阅读闭包(javascript),它们总是引用内部函数。

var pet = function(name) {   
  var getName = function() {
    return name;                          
  }
  return getName;           
}
myPet = pet('Vivie');
myPet();

为什么我们不想分离getName函数并引入一个'name'参数,以便我们可以独立地调用它?

var pet = function(name){
  return getName();
}
function getName(name){
  return name;
}

谢谢,我对javascript很陌生

1 个答案:

答案 0 :(得分:0)

尝试这篇文章。 Simple guide to understand closure in JavaScript

我在这里复制了本文解释的部分代码。 运行此代码段以查看内部函数的行为。

<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>