问题描述
我知道我可以从 VBScript 调用 JS 中定义的顶级函数,反之亦然,像这样:
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>
我还可以将 JS 包含到 VBScript 模块中,如下所示:
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>
...并且在includedModule.js 中定义的函数在VBScript 中可用.
...and the functions defined in the includedModule.js are available in the VBScript.
但是假设我有一个使用原型 OO 定义的 Javascript 类,如下所示:
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() { .. };
}());
如何使用 VBScript 中的对象(又名类型或类)?
How can I use that object (aka type, or class) from VBScript?
原版方法...
Dim foo
Set foo = New MyObj
...不起作用.
也没有
Dim foo
foo = MyObj()
...因为显然 this
在调用 JS 函数时没有定义来自 VBScript.或者其他的东西.
...because apparently this
is not defined when the JS function is invokedfrom VBScript. Or something.
那我该怎么办呢?
这是有价值的原因:在 Javascript 中有可用的 OO 库,从 VBScript 使用它会很有趣.
The reason this is valuable: there are OO libraries available in Javascript, that would be interesting to use from VBScript.
推荐答案
我不知道如何避免 VBScript 无法直接调用 Javascript构造函数"函数的问题.我处理它的方法是简单地定义一个 shim:一个 Javascript 中的顶级函数,它从 Javascript 中调用构造函数并返回引用.
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.
所以:
<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>
这篇关于如何在 ASP-Classic 或 WSH 环境中使用来自 VBScript 的 Javascript OO 类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!