How to reference a JScript file from another one?

前端 未结 3 1761
囚心锁ツ
囚心锁ツ 2020-12-15 09:56

I am writing some server-side scripts using JScript and WSH. The scripts are getting quite long, and some common functions and variables would fit better in a general librar

相关标签:
3条回答
  • 2020-12-15 10:17

    Based on Thomas's solution — here's a similar, but more modular approach. First, the script to call:

    /* include.js */
    (function () {
        var L = {/* library interface */};
        L.hello = function () {return "greetings!";};
        return L;
    }).call();
    

    Then, in the calling script:

    var Fs = new ActiveXObject("Scripting.FileSystemObject");
    var Lib = eval(Fs.OpenTextFile("include.js", 1).ReadAll());
    WScript.echo(Lib.hello()); /* greetings! */
    

    Libraries defined this way don't produce or rely on any upvalues, but the eval will return any value it receives from the surrounding anonymous-function in the library.

    0 讨论(0)
  • 2020-12-15 10:28

    OK, I found a decent solution:

    // A object to which library functions can be attached
    var library = new Object;
    eval((new ActiveXObject("Scripting.FileSystemObject")).OpenTextFile("common_script_logic.js", 1).ReadAll());
    
    // Test use of the library
    library.die("Testing library");
    

    I create an object to which I can attach my library functions. That way, I can reach code defined in my library from the calling script. Not perfect, but quite acceptable.

    It would be great to see a more proper solution :-)

    0 讨论(0)
  • 2020-12-15 10:30

    Try using a Windows Script File. It's basically an XML document which allows you to include multiple script files and define multiple jobs, amongst other things.

    <!-- MyJob.wsf -->
    <job id="IncludeExample">
      <script language="JScript" src="MyLib1.js"/>
      <script language="JScript" src="MyLib2.js"/>
      <script language="JScript">
        WScript.Echo(myLib1.foo());
        WScript.Echo(myLib2.bar());
      </script>
    </job>
    
    0 讨论(0)
提交回复
热议问题