Javascript-需要解释IIFE中的变量吗

Javascript-需要解释IIFE中的变量吗,javascript,frontend,web-frontend,Javascript,Frontend,Web Frontend,我有这段代码——我只是想知道为什么在我将'var'添加到foo变量之后,它就不起作用了(它显示foo是未定义的)。。。有人能解释一下这两个功能吗?谢谢 window.onload = function() { var test = foo().steps(2); console.log(test); } (function() { //if I remove var, then it prints out a function which is what I expecte

我有这段代码——我只是想知道为什么在我将'var'添加到foo变量之后,它就不起作用了(它显示foo是未定义的)。。。有人能解释一下这两个功能吗?谢谢

window.onload = function() {
    var test = foo().steps(2);
    console.log(test);
}

(function() {
  //if I remove var, then it prints out a function which is what I expected
  var foo = function() {
    var steps = 1;
    function callMe(g) {
      //do something else
      console.log("hello" + g);
    }
    callMe.steps = function(x) {
      //if no arguments then return the default value
      if (!arguments.length) return steps;
      console.log(arguments);
      //otherwise assign the new value and attached the value to callMe
      steps = x;
      return callMe;
    }
    return callMe;
  }
})();

var
添加到foo会使foo成为IIFE内部的局部变量,因此您无法在外部访问它。

因为
var
变量是函数作用域。您在声明它的函数之外使用
foo
。关于如何使它在作用域之外可访问,有什么想法吗?@AlexanderO'Mara的可能重复链接非常有用。。。谢谢。你能建议如何将foo公开给外部吗?@catlovespurple在函数外部声明
foo
,并在函数内部定义它。@Xufox你能写一些代码来说明你的建议吗?很难准确理解你在这里的意思…@catlovespurple在写评论之前,你在谷歌上搜索过“javascript变量声明”或“javascript变量范围”吗?@catlovespurple declare
var foo在生命外部,并在生命内部分配foo