如果将全局变量定义为"0",为什么将变量"closed"记录为"false"? [英] Why is the variable `closed` being logged as `false`, if I define it globally as `0`?

查看:32
本文介绍了如果将全局变量定义为"0",为什么将变量"closed"记录为"false"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这一定是非常基础的内容,但我不了解示波器的工作原理.我希望在整个JavaScript文件中都知道 closed 变量.

I know this must be really basic stuff but I don’t understand how the scope is working. I want the closed variable be known in the entire JavaScript file.

我有类似的东西(在jQuery中):

I have something like that (in jQuery):

var closed = 0;

$(function(){
  console.log(closed);
});

但是 closed 被记录为 false .我用 load onload 函数尝试了很多事情,但是失败了.

But closed is getting logged as false. I tried many things with load and onload functions, but I failed.

推荐答案

使用 let 代替 var ,因为 closed 是一个全局变量由JavaScript运行时提供,因此要使其在代码范围内是本地的,可以使用 let 而不是 var 来将变量设置为全局范围,并考虑全局 closed 属性.

Use let instead of var as closed is a global variable used by JavaScript runtime so to make it local to the scope of the code you can use let instead of var which set the variable to global scope considering the global closed property.

let closed=0;
$( function() {
    console.log(closed);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

这篇关于如果将全局变量定义为"0",为什么将变量"closed"记录为"false"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆