简体   繁体   English

如何定位JS中的全局变量?

[英]how to locate the global variables in JS?

I'm trying to understand something with JS .. in the function below, which is the global variable?我试图用 JS .. 在下面的函数中理解一些东西,哪个是全局变量? can you please help me understand this?你能帮我理解这个吗?

(function() {
  let grade = {score: 100, status: "passing"};
  age = 45;
  var salary = 45000;

The variable age is an implicit global because it's just mentioned on the left side of an assignment, and not explicitly declared with var or let .变量age是一个隐含的全局变量,因为它只是在赋值的左侧提到过,并且没有用varlet显式声明。

In "strict" mode that would be an error.在“严格”模式下,这将是一个错误。

Undeclared variables are always global.未声明的变量总是全局的。

Thus the variable age is the global variable.因此变量年龄是全局变量。

 (function() { let grade = {score: 100, status: "passing"}; age = 45; var salary = 45000; })(); console.log(window.age); //45 console.log(window.salary);//undefined console.log(window.grade); //undefined

如果您没有在未声明的变量前添加 var,Javascript 将假定它是一个全局变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM