简体   繁体   中英

Correct scope outside a function in Javascript

My question is regarding the below code:

var z='1'; 
(function(){ 
   y='2'; 
   console.log(z+y); // '12'
})();
console.log(z+y); // '12'

How come 'y' is accessible outside the function's scope?

You declared y like this y='2'; By not putting the var keyword in front of it, the variable automatically becomes global.

前面没有var的关键字被声明为全局变量。

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