如何为另一个函数声明变量,而不将其作为其他函数的参数传递

How to declare variables for another function without passing it as argument of other function?

本文关键字:函数 其他 参数传递 另一个 声明 变量      更新时间:2023-09-26

我想知道该怎么做?

例如

function get() {
   alert(s);
}
function declare() {
   var s = "Blah";
   get();
}

但我得到了s is not defined

我知道我们可以把它作为自变量传递,也可以把它设置为全局变量,但如果没有这两者,怎么办?

您可以使用闭包:

function declare() {
   var s = "Blah";
   function get() {
      alert(s);
   }
   get();
}