Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
726 views
in Technique[技术] by (71.8m points)

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...