首页 > 解决方案 > 如何在javascript中更改嵌套函数中的函数变量?

问题描述

我正在尝试更改嵌套函数中函数内声明的变量的值。但它不起作用。这是一个例子

function foo() {
  var str = "";

  function foo1() {
    str = "hello";
  }
  foo1();

  alert(str); // it shows nothing
}
<input type="button" onclick="foo()">

标签: javascript

解决方案


您可能希望将字符串设置为foo1().

function foo() {
    function foo1(){
        return "bar";
    }
    var str = foo1();
    alert(str);// it shows "bar"
}

foo();

推荐阅读