在脚本的编写中,我们经常会遇到自定义类,在使用自定义类中,会遇到一些问题:无法new自定义类,报错的现象。
来模拟一下场景:新建了一个脚本文件Action1,并加载一个Function.vbs文件。
脚本:
'实例化脚本段 Dim myTest Set myTest = new Test myTest.T1 Set myTest = Nothing
'Class脚本段 Class Test Function T1 msgbox "Test" End Function End Class |
分析:
1. 将所有脚本写入Action1中,运行,发现脚本Pass。
2. 将【Class脚本段】放入Function.vbs中,运行脚本,报“类没有被定义”的错,Fail。
3. 将【实例化脚本段】和【Class脚本段】都放入Function.vbs,脚本运行Pass。
小结:
【1】
所以单从位置上来说,要么【实例化脚本段】和【Class脚本段】都放在Action下,是可行的。
【2】
要么【实例化脚本段】和【Class脚本段】都放在Function.vbs下,运行不会出错。
【3】:
又想要将Class写入外部文件,又不想直接实例化。当然,还有些别的方法:
将【Class脚本段】写入Function.vbs中,并在Function.vbs中写入:
'===================== 'Test实例化的函数 '===================== Function newTest() Set newTest = new Test End Function |
这样,在Action1中只要这么写:
'实例化脚本段 Dim myTest Set myTest = newTest myTest.T1 Set myTest = Nothing |
也是可以正常使用的。
【4】
也可以不使用自带的添加Function.vbs文件到Function Libraries中,而是使用ExecuteFile的方法动态添加。
在Action1中写入:
ExecuteFile "D:\Test\Function.vbs" |
这样就不需要写Function newTest()函数,便可在所有地方进行new自定义类了。