Javascript 将局部变量从一个函数传递到另一个函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10579713/
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
Passing a local variable from one function to another
提问by user1393266
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
?
问题是:如何从我的第二个函数访问变量x
(在函数中声明show
)trig
?
回答by Pranay Rana
First way is
第一种方式是
function function1()
{
var variable1=12;
function2(variable1);
}
function function2(val)
{
var variableOfFunction1 = val;
// Then you will have to use this function for the variable1 so it doesn't really help much unless that's what you want to do. }
// 然后你将不得不对变量 1 使用这个函数,所以它并没有多大帮助,除非这是你想要做的。}
Second way is
第二种方式是
var globalVariable;
function function1()
{
globalVariable=12;
function2();
}
function function2()
{
var local = globalVariable;
}
回答by Asim Mahar
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();
回答by Ankit Jain
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();
// 在源代码中使用 window.var1= oEvent.getSource().getBindingContext();
// Get value of var1 in destination var var2= window.var1;
// 获取目标中 var1 的值 var var2= window.var1;