将局部变量从一个函数传递到另一个函数

时间:2021-03-23 16:45:07

I am a beginner in JavaScript and wanted to ask the following: I have two simple functions and was wondering if there is any way to pass a variable value from one function to another. I know I can just move it outside the function to be used in other functions as well but just need to know the way how I can have one local variable and manipulate with it in my second function. Is this possible and how?

我是JavaScript的初学者,想要问以下内容:我有两个简单的函数,并且想知道是否有任何方法可以将变量值从一个函数传递到另一个函数。我知道我可以将它移到函数之外以便在其他函数中使用,但只需要知道如何在第二个函数中使用一个局部变量并使用它进行操作。这可能吗?怎么样?

Here is some code:

这是一些代码:

window.onload = function show(){
    var x = 3;
}

function trig(){
    alert(x);
}
trig();

The question is: how do I access variable x (declared in the function show) from my second function trig?

问题是:如何从我的第二个函数trig访问变量x(在函数show中声明)?

3 个解决方案

#1


34  

First way is

第一种方式是

function function1()
{
  var variable1=12;
  function2(variable1);
}

function function2(val)
{
  var variableOfFunction1 = val;
}

Second way is

第二种方式是

var globalVariable;
function function1()
{
  globalVariable=12;
  function2();
}

function function2()
{
  var local = globalVariable;
}

#2


0  

Adding to @pranay-rana's list:

添加到@ pranay-rana的列表:

Third way is:

第三种方式是:

function passFromValue(){
    var x = 15;
    return x;  
}
function passToValue() {
    var y = passFromValue();
    console.log(y);//15
}
passToValue(); 

#3


-1  

You can very easily use this to re-use the value of the variable in another function.

您可以非常轻松地使用它在另一个函数中重用变量的值。

// Use this in source window.var1= oEvent.getSource().getBindingContext();

//在源窗口中使用它.var1 = oEvent.getSource()。getBindingContext();

// Get value of var1 in destination var var2= window.var1;

//在目标var var2 = window.var1中获取var1的值;

#1


34  

First way is

第一种方式是

function function1()
{
  var variable1=12;
  function2(variable1);
}

function function2(val)
{
  var variableOfFunction1 = val;
}

Second way is

第二种方式是

var globalVariable;
function function1()
{
  globalVariable=12;
  function2();
}

function function2()
{
  var local = globalVariable;
}

#2


0  

Adding to @pranay-rana's list:

添加到@ pranay-rana的列表:

Third way is:

第三种方式是:

function passFromValue(){
    var x = 15;
    return x;  
}
function passToValue() {
    var y = passFromValue();
    console.log(y);//15
}
passToValue(); 

#3


-1  

You can very easily use this to re-use the value of the variable in another function.

您可以非常轻松地使用它在另一个函数中重用变量的值。

// Use this in source window.var1= oEvent.getSource().getBindingContext();

//在源窗口中使用它.var1 = oEvent.getSource()。getBindingContext();

// Get value of var1 in destination var var2= window.var1;

//在目标var var2 = window.var1中获取var1的值;