You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript如何访问另一个函数内的变量完成求和计算?

问题原因

你当前代码无法获取变量是因为JavaScript中var声明的变量拥有函数作用域,在fun2内部声明的two、three只能在fun2的函数体内访问,外部函数fun1默认无法直接读取。

方法1:将需要的变量作为返回值传递

修改fun2返回你需要的两个变量,在fun1中调用fun2获取值后计算:

fun1();

function fun1() {
  // 调用fun2拿到目标变量
  const { two, three } = fun2();
  alert("var two + var three = " + (two + three));
}

function fun2() {
  var one = 1;
  var two = 2;
  var three = 3;
  var four = 4;
  // 返回需要暴露的变量
  return { two, three };
}

注意:求和的时候要把two + three用括号包裹,否则会被当做字符串拼接,得到23而不是5

方法2:提升变量到公共作用域

如果变量需要在多个函数内复用,可以把变量声明在两个函数之外的公共作用域:

// 公共作用域声明变量
var two, three;
// 先调用fun2完成变量赋值
fun2();
fun1();

function fun1() {
  alert("var two + var three = " + (two + three));
}

function fun2() {
  var one = 1;
  two = 2;
  three = 3;
  var four = 4;
}

方法3:使用闭包封装

如果不想污染全局作用域,可以用闭包把相关函数和变量封装在一起:

const counter = (function() {
  var one = 1;
  var two = 2;
  var three = 3;
  var four = 4;
  return {
    fun1: function() {
      alert("var two + var three = " + (two + three));
    }
  }
})()

counter.fun1();

内容的提问来源于stack exchange,提问作者irureta

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 19:15:02