Misunderstanding records for variables defined by var

Problems needing attention when var defines variables

The variable defined by var in the function scope is a local variable and cannot be referenced externally, while in the global scope, it is a global variable

//demo1
if(1){
    
    //var没有块级作用域这个说法,所以在此定义的var属于全局变量
    var a = 1;
}
console.log(a) //1

============================================
function fun() {
    
    
    var a = 1;
}
fun()
console.log(a) //a is undefined

And var has different situations in different execution environments

in browser environment

Will become a property of the global object window

var a = 1;
console.log(window.a)//1
//等价于
a = 1;
console.log(window.a)//1

in the node environment

It will not be a property of the global object global

var a = 1;
console.log(global.a) //a is undefined
//不等价于
a = 1;
console.log(global.a) //1

Because the global object is independent of all js files in the node environment , it can be understood that it belongs to the global object of the entire project , so defining a variable in a js file varcan only be used in the current js file

Guess you like

Origin blog.csdn.net/Laollaoaolao/article/details/126677870