When I was writing a program in the afternoon, I encountered a problem of variable redefinition. Specifically, the same variable was defined in two places in a function, and the two variables were placed in two parts of the IF statement. I originally thought that the two definitions in different blocks in the statement should have no effect. However, during operation, IIS prompted the variable to be redefinition, and removing the duplicate definition is correct.
After solving the problem, I suddenly thought of reading an article in Fdream's blog "JavaScript Variables No Block-level Scope". It seems that these two are similar. In VBScript, variables also have no block-level scope.
After reading that article again, I also did an experiment and got the result: In VBScript, the scope of the variable defined in the function is the entire function, not the block level, no matter where the variable is defined in the function. Therefore, a variable in a function can be used throughout the function no matter where it is defined in the function.
Here are some examples to illustrate this problem.
The code copy is as follows:
OptionExplicit
Subfoo()
Dimvar
var="hello,world!"
MsgBoxvar
EndSub
Callfoo()
The following code is equivalent to the above code, but the definition of var is placed at the end of the function:
The code copy is as follows:
OptionExplicit
Subfoo()
var="hello,world!"
MsgBoxvar
Dimvar
EndSub
Callfoo()
The following example shows that no matter where the variable is defined, it can be used in the entire function. Of course, if the definition is placed in a special position, it will be beneficial to the clarity of the code, it is more convenient to read and modify it.
The code copy is as follows:
OptionExplicit
Subfoo()
Dimvar1
var1="YES"
MsgBox"var1:"&var1&vbCrLf&"var2:"&var2
IFvar1="YES"Then
Dimvar2
var2="NO"
EndIF
MsgBox"var1:"&var1&vbCrLf&"var2:"&var2
EndSub
Callfoo()
In ASP development, the usual practice when writing a function is to define the variable until it is used. Although the scope of the variable has nothing to do with the position of the definition, I think it is better to write it before the variable is used. It is more convenient to modify the code in the future, so you don’t have to turn to the function header to modify the variable definition after modifying it.