Creating JScript Objects Using IScriptControl

Is there a better way to create objects in an IScriptControl than this?

Result := SC.Eval('new Date()');

      

I need something like this:

function CreateJSObject(JSClassName: string; Params: PDispParams): OleVariant; 

      

naive implementation would be

var 
    S: string;
begin 
    S := '';
    for I := P.cArgs - 1 downto 0 do
    begin
        if S <> '' then
            S := S + ', ';
        S := S + ConvertParamToJSSyntax(OleVariant(P.rgvarg[I]));
    end;
    Result := ScriptControl.Eval('new ' + JSClassName + '(' + S + ');'); 
end;

      

+2


source to share


2 answers


Request the IDispachEx interface in the CodeObject property for MSScriptControl. This is a pointer to the global JScript state and contains all objects added to it. Then execute InvokeEx with DISPATCH_CONSTRUCT on the object name you want to create. This will be equivalent to calling "new".

This will create an object of the correct type and you don't have to convert them to javascript types. You can also pass your own objects to the constructor.



I know this works for constructors defined in the script. I'm not sure if Date is a native property.

This works for JScript and VBScript activescripting host, but some other scripting hosts don't return anything to CodeObject, so it's not very portable.

+1


source


To call a subroutine, you need to use the Run method instead of Eval. See this document for details .

You are right when you say that "constructors are different methods", but in this case you are actually just returning the newly constructed value, right? And so I expect to still be able to use Eval ().

The following code works for me:



procedure TForm1.Button1Click(Sender: TObject);
var
  ScriptControl: Variant;
  Value: Variant;
begin
  ScriptControl := CreateOleObject('ScriptControl');
  ScriptControl.SitehWnd := Handle;
  ScriptControl.Language := 'JScript';

  Value := ScriptControl.Eval('new Date();');
  ShowMessage(VarToStr(Value));
end;

      

When I click the button, my ShowMessage appears with "Wed Sep 16 23:37:14 TC + 0200 2009".

So, to return a value from a constructor, you can actually use Eval ().

0


source







All Articles