[This] post talks about the variables scopes in Javascript. Here, we will turn to VBScript for similar investigation upon the variable scopes. There is no closure (inner function) in VBScript, and it is therefore simpler. The VBScript, like Javascript (JScript) is not an independent programming language. It needs to be running on a hosting environment (e.g browser, windows scripting host).
At the begining (only at the first statement), you can choose to define:
Option Explicit
This allows the VBScript interpreter to check if the variables have been defined using the keyword dim before they are referenced/used.
The first case is simple to understand, inside the function/procedure, the global variable is accessed/changed as expected.
Option Explicit
Dim global: global = 1
Sub Test
global = 2
End Sub
MsgBox global 'print 1
Test
MsgBox global 'print 2
If we declare the variables inside procedure/function using keyword dim similar to the var in Javascript, like this, we can prevent changing the global variable by creating a local copy, although the names are identical.
Option Explicit
Dim global: global = 1
Sub Test
Dim global
global = 2 'local copy actually
End Sub
MsgBox global 'print 1
Test
MsgBox global 'print 1
Without the Option Explicit, you can access a variable even if they are not defined. The following shows that with the keyword dim inside a function/procedure, anything defined stay within the local scope.
Sub Test
Dim global
global = 2 ' still local copy
End Sub
MsgBox global 'print nothing
Test
MsgBox global 'print nothing
However, without dim, the procedure will create a global variable.
Sub Test
global = 2 ' assign to global scope
End Sub
MsgBox global 'print nothing
Test
MsgBox global 'print 2
–EOF (The Ultimate Computing & Technology Blog) —
352 wordsLast Post: Open A Excel File using VBScript @ Windows Script Host
Next Post: VBScript at Window Script Host, Check Folder Exists