繁体   English   中英

从内部函数访问外部函数变量

[英]Access outer function variables from inner function

如何在函数B()中更改函数A()中的x

function A() {
    var x = 10; // Value to be changed
    function B() {
        var x = 20;
        // From here i want to change the value of x (i.e. x=10 to x=40)
    }
    B();
}

A();

打算覆盖变量时不要使用var 使用var创建一个新变量,该变量在声明它的作用域的本地。 这就是为什么x不在外面改变的原因。

function A() {
    var x = 10;
    function B() {
        x = 20; // change x from 10 to 20
    }

    B(); // x is now changed
}

如果我理解您的问题,以下代码是一个解决方案:

function A() {
    var x = 10; // Value to be changed
    function B() {
        var x = 20;
        // From here i want to change the value of x (i.e. x=10 to x=40)
        changeX(40);
    }
    function changeX(y) {
        x = y;
    }
    B();
    alert(x);
}

A();

但是有更优雅的方法,但这取决于您的应用程序。

也许:

function A() {
    var x = 10; // Value to be changed
    function B() {
        var x = 20;
        return x; // Return new value of x
    }
    x = B(); // Set x to result returned by B(), i.e. the new value
}

A();

var语句将创建新的局部变量。 所以在你的例子中:

function A() {
    var x = 10; // You can think of it as A.x
    function B() {
        var x = 20; // And this as A.B.x
    }
}

这两个变量属于不同的范围,如果要从内部范围内访问外部作用域的变量,只需访问它,而不重新声明它。

您可能需要查看http://www.planetpdf.com/codecuts/pdfs/tutorial/jsspec.pdf上提供的“JavaScript语言规范”文档,以了解范围,语句和其他基础知识如何在JavaScript中运行。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM