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

问题描述

我知道这一定是非常基本的东西,但我不明白示波器是如何工作的.我希望在整个 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.我用 loadonload 函数尝试了很多东西,但我失败了.

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

推荐答案

Use 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"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-17 20:08