سؤال

I have used Date.prototype in my WSH-JScripts to do some date calculations. I would like to include these functions in WSH-VBS as well. Basically, mixing JS and VBS code and including JS files in a VBS script works in WSF files.

But I can't get the extended Date object to work in VBS. I suppose that is because there is no equivalent Date object in VBS, and dates are handled in another way in VBS.

Reimplementing my date functions in VBS seems to be a bad idea (as long as I don't know for sure that there is no other way). It could be possible to write simple JS wrappers in the VBS script which sort of forward to the Date objects functions.

If there is any other idea, I'd be very happy to see it.

هل كانت مفيدة؟

المحلول

The following script worked for me on Windows 7. I think the key is having a pair of functions to translate between the JScript Date object and the VBScript Date type. The JSDateFromVB in my example is a very crude function that translates from VBScript Date to JScript Date.

<job id="test">
    <script language="JScript">
        if (typeof Date.prototype.prettyPrint === 'undefined')
        {
            Date.prototype.prettyPrint = function () {
                return this.getFullYear() + '-' +
                    (this.getMonth()+1) + '-' +
                    this.getDate();
            }
        }

        function makeDate(vbDate) {
            return new Date(vbDate);
        }
    </script>
    <script language="VBScript">
        Dim d
        d = DateSerial(2000, 11, 30)

        Dim js_d
        Set js_d = JSDateFromVB(d)

        WScript.Echo js_d.prettyPrint()

        Function JSDateFromVB(pDate)
            Set JSDateFromVB = makeDate(pDate)
        End Function
    </script>
</job>

نصائح أخرى

The reason your extensions to the Date object in JavaScript aren't working in VBScript is that the WSH system doesn't notice an extension to the prototype of any JavaScript object. The prototype definition only exists within the JavaScript code you write - as soon as you try to access it from within the VBScript, it doesn't exist because it was never imported in to that namespace.

You can hack it in however - by defining the prototype extension within a normal JavaScript function (which is one of the two items that get imported - I believe the other is global variables). The prototype extension would only exist on JavaScript Date objects however - you cannot extend VBScript objects.

function blargh() {
  Date.prototype.help = function() {...};
  ...
}

... then in your VBScript, you would call "blargh()" which would modify the Date object in JavaScript so that any Date object returned to VBScript would have the "help()" sub-function available with it.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top