Javascript 我如何在javascript中的函数之间传递变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4600508/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 13:11:47  来源:igfitidea点击:

How do i pass variables between functions in javascript

javascriptfunctionvariables

提问by Hussein

Here are 2 functions in the simplest form. I'm working with jquery. What is the best way to pass var str from the first function to the second one.

这是最简单形式的 2 个函数。我正在使用 jquery。将 var str 从第一个函数传递到第二个函数的最佳方法是什么。

function a() {
    var str = "first";
};

function b() {
    var new = str + " second";
};

回答by Nick Craver

You need to either pass it between them, or it seems from your example, just declare it in a higher scope:

您需要在它们之间传递它,或者从您的示例看来,只需在更高的范围内声明它:

var str;
function a(){
  str="first";
}
function b(){
  var something = str +" second"; //new is reserved, use another variable name
}

回答by Jacob Relkin

Use function parameters, like this:

使用函数参数,像这样:

function a() {
   var str = "first";
   b(str);
}

function b(s) {
   var concat = s + " second";
   //do something with concat here...
}

You couldjust declare a variable higher up in the scope chain, but I opt to use arguments to restrict variable access to only the contexts that absolutely need it.

可以在作用域链的更高层声明一个变量,但我选择使用参数将变量访问限制在绝对需要它的上下文中。

Oh yeah, isn't that called the principle of least privilege?

哦对了,这不就是所谓的最小特权原则吗?