Create instance for a class(resides in B.vbs) from another .VBS file

前端 未结 4 755
迷失自我
迷失自我 2020-12-11 23:04

I have 2 vbs files.

A.vbs:

Class test
  public a
  public b
End Class

B.vbs:

Dim objShell         


        
4条回答
  •  天涯浪人
    2020-12-11 23:26

    .Running a .vbs won't make the code usable in another one. A simple but extensible strategy is to use .ExecuteGlobal on the 'libraries'. Given

    Lib.vbs:

    ' Lib.vbs - simple VBScript library/module
    ' use
    '  ExecuteGlobal goFS.OpenTextFile().ReadAll()
    ' to 'include' Lib.vbs in you main script
    
    Class ToBeAShamedOf
      Public a
      Public b
    End Class ' ToBeAShamedOf
    

    and main.vbs:

    ' main.vbs - demo use of library/module Lib.vbs
    
    ' Globals
    Dim gsLibDir : gsLibDir = ".\"
    Dim goFS     : Set goFS = CreateObject("Scripting.FileSystemObject")
    
    ' LibraryInclude
    ExecuteGlobal goFS.OpenTextFile(goFS.BuildPath(gsLibDir, "Lib.vbs")).ReadAll()
    
    WScript.Quit main()
    
    Function main()
      Dim o : Set o = New ToBeAShamedOf
      o.a = 4711
      o.b = "whatever"
      WScript.Echo o.a, o.b
      main = 1 ' can't call this a success
    End Function ' main
    

    you'll get:

    cscript main.vbs
    4711 whatever
    

    (cf. this answer for a seed of a useful class)

提交回复
热议问题