【发布时间】:2019-02-12 04:50:16
【问题描述】:
在 JS here 中研究全局变量,我开始尝试它,令我惊讶的是:
var thisVar = "global var";
function showVarLet() {
var thisVar = "local var";
console.log("%s %s", thisVar, window.thisVar);
}
showVarLet();
给我:
local var
undefined
但在浏览器控制台中相同,给了我:
local var
global var
那么,这个窗口对象是什么?
编辑:
我尝试在控制台中检查如果我引用this.thisVar 而不是window.thisVar 会发生什么,我的假设是我会访问局部变量但我继续访问全局变量,为什么会这样?
【问题讨论】:
-
“给我:
local var undefined” 在哪里? -
在 sn-p 中得到正确的输出
-
好吧,你在上面说
gives me的运行时执行@ -
您可能已经在 jsfiddle 或 plunker 之类的网站上运行过它。它会给你
undefined,因为它们通常将代码包装在javascript部分中的函数stackoverflow.com/questions/33080320/… -
我刚刚写了一个 html 文件,将代码放入
<script>,创建了一个类似<button type="button" onclick="global()">Global</button>的按钮,我展示的代码在我的<script>标签内的一个名为global()的函数中.然后我只需在 Chrome 或 Firefox 中打开这个 html 并点击按钮。
标签: javascript global-variables