TypeScript Variable scope

The scope of a variable refers to the range of validity of the variable , It is the code range that user-defined variables can use , It is closely related to the position of variable definition .

TypeScript There are several scopes : Global scope 、 Local scope 、 Class scope .

Global scope

Global variables can be used anywhere in your code .

Local scope

A local variable can only be used in a code block or method that declares it .

Class scope

This variable can also be called “ Class variables ” perhaps “ Object variables ”. It should be noted that , There are obvious differences between the two : Class variables are also called static variables , That is, add... Before the variable static The variable of ; Object variables are also called instance variables , I didn't add it static The variable of . The difference between class variables and object variables is : Class variables are common to all objects , One of the objects changes its value , What other objects get is the result of the change ; Object variables are object private , An object changes its value , Does not affect other objects .

Illustrate with examples

The following examples illustrate the use of three scopes :

var global_num = 12          //  Global variables 
class Numbers { 
   object_num = 13;             //  Instance variables 
   static static_num = 10;      //  Static variables 
   
   storeNum():void { 
      var local_num = 14;    //  local variable 
   } 
} 
console.log(" The global variable is : " + global_num)  
console.log(" The static variable is : " + Numbers.static_num )
var obj = new Numbers(); 
console.log(" Instance variables : "+obj.object_num)

The above code uses tsc The command is compiled as JavaScript The code is :

var global_num = 12; //  Global variables 
var Numbers = /** @class */ (function () {
    function Numbers() {
        this.object_num = 13; //  Instance variables 
    }
    Numbers.prototype.storeNum = function () {
        var local_num = 14; //  local variable 
    };
    Numbers.static_num = 10; //  Static variables 
    return Numbers;
}());
console.log(" The global variable is : " + global_num);
console.log(" The static variable is : " + Numbers.static_num);
var obj = new Numbers();
console.log(" Instance variables : " + obj.object_num);

Perform the above JavaScript Code , The output is :

 The global variable is : 12
 The static variable is : 10
 Instance variables : 13

If we call local variables outside the method local_num, Will report a mistake :

error TS2322: Could not find symbol 'local_num'.

Link to the original text :http://www.mybatis.cn/typescript/1979.html