将局部变量从一个函数传递给另一个函数 [英] Passing a local variable from one function to another

查看:381
本文介绍了将局部变量从一个函数传递给另一个函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是JavaScript的初学者,想问以下问题:我有两个简单的函数,想知道是否有任何方法可以将变量值从一个函数传递给另一个函数.我知道我可以将其移动到其他函数中,也可以在其他函数中使用,但是只需要知道如何拥有一个局部变量并在第二个函数中对其进行操作的方式即可.这有可能吗?

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?

这是一些代码:

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

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

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

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

推荐答案

第一种方法是

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

function function2(val)
{
  var variableOfFunction1 = val;

//然后,您将不得不对该变量1使用此函数,因此除非您要这样做,否则它实际上并没有太大帮助. }

// 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. }

第二种方法是

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

function function2()
{
  var local = globalVariable;
}

这篇关于将局部变量从一个函数传递给另一个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆