简体   繁体   中英

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? 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 .

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 将假定它是一个全局变量。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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