VBScript 中变量的作用域 [英] Scope of a variable in VBScript

查看:30
本文介绍了VBScript 中变量的作用域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下代码:

Option Explicit

Dim Count : Count = 4


'Case-I
Sub Display1()

 MsgBox(Count)

End Sub

'Case-II

Sub Display2(Count)

 MsgBox(Count)

End Sub

混乱

  • 如果变量 Count 可以被两者访问method 还是只针对 Display2 方法?
  • 如果变量 count 不能通过 Display1 方法访问,那么有没有办法让它在任何子或函数中可用不将其传递给 SubFunction
  • 现在,如果我更新了 Display2 子中的 Count 变量该值可用于其他 functionsub,前提是VBScript 具有global 变量声明.
  • here should the variable Count will be accessible to the both method or only to the Display2 method?
  • If the variable count is not accessible with Display1 method,then is there any way to make it useable within any sub or function without passing it to that Sub or Function
  • Now if I updated the Countvariable from the Display2 sub will that value can be used to other function or sub provided that VBScript has global variable declarations.

推荐答案

变量 count 在任何函数或子过程之外声明,因此它的作用域在这里是全局的.全局变量可以在任何函数或子过程中使用,其值可以在程序流程的任何地方改变.

Variable count is declared outside of any function or sub-procedure, hence its scope is global here. Global variable can be used in any function or sub-procedure and its value can be change in anywhere in program flow.

现在,如果您调用此过程并运行 .vbs 文件,则消息框将在两种情况下显示 4.

Now if you make call to this procedure and run the .vbs file, message box will display 4 in both cases.

Option Explicit

Dim Count : Count = 4
'Case-I
Sub Display1()
 MsgBox(Count)
End Sub

'Case-II
Sub Display2(Count)
 MsgBox(Count)
End Sub

Call Display1()
Call Display2(Count)

如果你在任何函数或子过程中改变了count变量的值,它的值也会随着其他过程的变化而改变,因为它的作用域是全局的.

If you change value of count variable in any function or sub procedure, its value will change for other procedure also as its scope is global.

选项显式

Dim Count : Count = 4
'Case-I
Sub Display1()
 Count = 5               ''value changed here 
 MsgBox(Count)
End Sub

'Case-II
Sub Display2(Count)
 MsgBox(Count)
End Sub

Call Display1()
Call Display2(Count)

在上述情况下,两个消息框都会显示5

In above case, both message box will display 5

这篇关于VBScript 中变量的作用域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆