How can I use Javascript OO classes from VBScript, in an ASP-Classic or WSH environment?

筅森魡賤 提交于 2019-12-18 09:26:08

问题


I know I can call top-level functions defined in JS from VBScript, and vice versa, like this:

<%@ language="Chakra" %>

<script language='JavaScript' runat='server'>
  function jsFunction1() {
      for (var i=0;i<10;i++) Response.Write(i+"<br>");
      vbFunction2();
  }
</script>

<script language='VBScript' runat='server'>
  Sub vbFunction1 ()
      Response.Write("VB Hello <br/>" & VbCrLf)
      jsFunction1()
  End Sub
  Sub vbFunction2 ()
      Response.Write("VB Goodbye <br/>" & VbCrLf)
  End Sub
</script>


<script language="JavaScript" runat="server">
  vbFunction1();
</script>

I can also include JS into VBScript modules, like this:

<%@ language="VBScript" %>

<script language="Javascript" runat="server" src="includedModule.js"></script>

<script language="VBScript" runat="server">

    ....
</script>

...and the functions defined in the includedModule.js are available in the VBScript.

But suppose I have a Javascript class defined using prototypal OO, like this:

(function() {

  MyObj = function() {
    this.foo = ...
    ...
  };

  MyObj.prototype.method1 = function() { .. };
  MyObj.prototype.method2 = function() { .. };
}());

How can I use that object (aka type, or class) from VBScript?

The vanilla approach...

Dim foo
Set foo = New MyObj

...does not work.

Neither does

Dim foo
foo = MyObj()

...because apparently this is not defined when the JS function is invoked from VBScript. Or something.

So how can I do it?

The reason this is valuable: there are OO libraries available in Javascript, that would be interesting to use from VBScript.


回答1:


I don't know how to avoid the problem that VBScript cannot directly call a Javascript "constructor" function. The way I dealt with it was to simply define a shim: a top-level function in Javascript that invokes the constructor from within Javascript and returns the reference.

So:

<script language='javascript' runat='server'>(function() {  
  MyObj = function() {  
    this.foo = ...  
    ...  
  };  

  MyObj.prototype.method1 = function() { .. };  
  MyObj.prototype.method2 = function() { .. };  

  // define a shim that is accessible to vbscript
  Shim = {construct: function() { return new MyObj(); } };

}());  
</script>

<script language='vbscript' runat='server'>
  Dim foo
  Set foo = Shim.construct()
   ...
</script>


来源:https://stackoverflow.com/questions/10080262/how-can-i-use-javascript-oo-classes-from-vbscript-in-an-asp-classic-or-wsh-envi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!