In the afternoon, when I write the program, I come across a variable redefinition problem, in particular, the same variable is defined in two places in a function, and two variables are placed in two parts of the IF statement, which would have been thought to be different blocks in the statement, and should have no effect, whereas in run IIS prompts for a variable redefinition, It is correct to remove the duplicate definition.
Solved the problem suddenly thought in Fdream blog read an article "JavaScript variable block-level scope", it seems that the two are similar, in VBScript, the variable also has no block-level scope.
After reading the article again, I did the following experiment and got the result: in VBScript, the scope of a variable defined in a function is the entire function, not the block level, regardless of where the variable is defined in the function. Therefore, a variable in a function can be used throughout a function regardless of where it is defined in the function.
Here are some examples to illustrate this problem.
Copy Code code as follows:
Option Explicit
Sub foo ()
Dim var
Var= "hello,world!"
MsgBox var
End Sub
Call Foo ()
The following code is equivalent to the above code, but the definition of VAR is placed at the end of the function:
Copy Code code as follows:
Option Explicit
Sub foo ()
Var= "hello,world!"
MsgBox var
Dim var
End Sub
Call Foo ()
The following example shows that the variables, regardless of the definition, can be used throughout the function, of course, if the definition of the location of a special point in favor of the clarity of the code, reading more convenient, the modification is also more convenient.
Copy Code code as follows:
Option Explicit
Sub foo ()
Dim var1
var1= "YES"
MsgBox "var1:" &var1&vbCrLf& "VAR2:" &var2
IF var1= "YES" Then
Dim var2
Var2= "NO"
End IF
MsgBox "var1:" &var1&vbCrLf& "VAR2:" &var2
End Sub
Call Foo ()
In ASP development, it is common practice to write a function when the variable is defined as although the scope of the variable and the location of the definition is irrelevant, but I think it is better to write in the variable before use, later to change the code to be more convenient, not to modify a piece of code and then turn to the function of the head to modify the definition of the variable.