简体   繁体   English

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

[英]How do I pass variables between functions in Javascript?

Here are 2 functions in the simplest form.这是最简单形式的 2 个函数。 I'm working with jquery.我正在使用 jquery。

What is the best way to pass var str from the first function to the second one?将 var str 从第一个函数传递到第二个函数的最佳方法是什么?

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

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

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 could just 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 ?哦对了,这不就是所谓的最小特权原则吗?

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
}

i use..我用..

 function a(){
 let str = "first";
 localStorage.setItem('value1', `${str}`);}

 function b(){
 let str = localStorage.getItem('value1');
 let new = str + " second";}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM