javascript - 如何在 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();
解决方案
由于此处尚未提及,我将添加另一种可能的方法,即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});
推荐阅读
- components - a-frame superhands 定制手模型
- python - 在 tqdm 中的 for 循环后更改描述
- xml - 搜索 xml 到 jekyll 转换器
- r - R:有没有办法在两个不同的 dfs 中找到与两个字符串列的相同第一个元素的部分字符串匹配?
- node.js - 向设备组 firebase node.js 发送通知
- javascript - 在工作表中自动发送电子邮件时自动检测日期
- c# - 如何在 Itext7 中使用任何印地语字体?
- vb.net - 字符串列表的大小
- flutter - 如何使用 add2calendar 包制作动态 Flutter 按钮?
- android-fragments - 如何使用导航组件配置 DrawerLayout