首页 > 解决方案 > 如何在 JavaScript 中从外部范围访问变量

问题描述

在下面的示例中,我试图访问x外部函数中的那个。

我期待得到 20 作为输出,但是输出是undefined.

有人可以解释为什么会发生这种情况,有没有办法访问外部 x?

var x = 10;
function outer() {
    var x = 20;
    function inner() {
        var x = 30;
        function printX() {
            console.log(outer.x);
        }
        printX();
    }
    inner();
}
outer();

标签: javascriptscope

解决方案


由于此处尚未提及,我将添加另一种可能的方法,即this通过调用函数来利用和作用域.apply(),如下所示:

var x = 10;
function outer() {
    var x = 20;
    function inner() {
        var x = 30;
        function printX() {
            // this now contains all 3 x variables without adding any parameters to any of the functions
            console.log("Window x:", this.windowX);
            console.log("Outer x:", this.outerX);
            console.log("Inner x:", this.innerX);
        }
        // pass through existing context (which we got from inner.apply(...) down below, as well as add
          // inner() x value to the new context we pass to printX() 
        printX.apply({...this, innerX: x});
    }
    // pass through existing context (which we got from outer.apply(...) down below, as well as add
      // outer() x value to the new context we pass to inner()
    inner.apply({...this, outerX: x});
}
// pass through window level x as "this" to outer(). Technically it's still available via window.x,
// but this will be consistent with the others
outer.apply({windowX: x});


推荐阅读