当前位置:网站首页>TypeScript:var

TypeScript:var

2022-07-01 14:47:00 Everything has changed every day

var Only variables defined Global scope and Function scope , There is no block scope .

Variables defined in a function belong to the scope of the function , The rest are global scopes .

Use var Defined variables can also be accessed before definition , The value is undfiend, This phenomenon is called Variable Promotion .

var a = 1;// Defined outside the function , Belongs to the global scope , Globally accessible 
function f()
{
	console.log(b);// Variable Promotion , Output undefined
	if(a == 1)// Variables with global scope can be accessed directly in the function 
	{
		var b = 2;// Defined in a block within a function , Belongs to the function scope , You can access... Only in functions 
	}
	console.log(b);// Access to b, Output 2
}
f();
console.log(b);// Cannot access b

Use var You can define the same variables repeatedly in the same scope , No mistake. :

var a = 1;
var a = "hello";
console.log(a);// Output hello

Use var Variables defined in functions , If the variable name is the same as that of the global scope , It will mask the visibility of global variables within the scope of the function :

var a = 1;
function f()
{
	var a = "hello";// Defined within the scope of the function a, Will shield the global scope a The visibility of , Yes a The access of only affects a
	console.log(a);// Within the scope of the output function a,hello
}
f();
console.log(a);// Output a, The value is 1

Because there is no block scope , Outside the scope of function for,while Variables defined in statement blocks such as are also considered as global scopes :

for(var a = 0, c=""; a < 10; a++) {// It is equivalent to defining i and c  
  var b = "";// Each cycle is redefined b
  b += (a + " ");
  c += (a + " ");
}
console.log(a); // You can access i, Output :10 
console.log(b); // Because each cycle is redefined b, So the output :9 
console.log(c); // You can access c, Output :0 1 2 3 4 5 6 7 8 9  

原网站

版权声明
本文为[Everything has changed every day]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202152358264238.html