AutoIt
AutoIt
Call a JavaScript Function Passing an Object Argument
See more JavaScript Examples
Demonstrates how to call a JavaScript function with an argument that is an object.Chilkat AutoIt Downloads
Local $bSuccess = False
; This is the JavaScript function we'll call:
; function describeCar(car) {
; console.log(`This is a ${car.year} ${car.make} ${car.model}.`);
; }
$oSbScript = ObjCreate("Chilkat.StringBuilder")
$oSbScript.Append("function describeCar(car) { console.log(`This is a ${car.year} ${car.make} ${car.model}.`); }")
$oJs = ObjCreate("Chilkat.Js")
$oResult = ObjCreate("Chilkat.JsonObject")
$oResult.EmitCompact = False
; Call Eval to add the function to the context's global object
$bSuccess = $oJs.Eval($oSbScript,$oResult)
If ($bSuccess = False) Then
; Examine the result for an exception.
ConsoleWrite($oResult.Emit() & @CRLF)
; Also examine the LastErrorText.
ConsoleWrite($oJs.LastErrorText & @CRLF)
Exit
EndIf
; ------------------------------------------------------------------------------
; Call the function describeCar(car)
$oFuncCall = ObjCreate("Chilkat.JsonObject")
$oFuncCall.EmitCompact = False
; Create JSON specifying the function name and arguments
; In this case, there is only 1 argument, and it is an object.
; {
; "name": "describeCar",
; "args": [
; {
; "make": "Toyota",
; "model": "Corolla",
; "year": 2022
; }
; ]
; }
$oFuncCall.UpdateString("name","describeCar")
; Create the JSON object that is the argument.
$oArg = ObjCreate("Chilkat.JsonObject")
$oArg.UpdateString("make","Toyota")
$oArg.UpdateString("model","Corolla")
$oArg.UpdateInt("year",2022)
; Create the arguments array.
$oArgsArray = ObjCreate("Chilkat.JsonArray")
$oArgsArray.AddObjectCopyAt(0,$oArg)
; Add the "args" array to the funcCall.
$oFuncCall.AppendArrayCopy("args",$oArgsArray)
ConsoleWrite($oFuncCall.Emit() & @CRLF)
$bSuccess = $oJs.CallFunction($oFuncCall,$oResult)
If ($bSuccess = False) Then
; Examine the result for an exception.
ConsoleWrite($oResult.Emit() & @CRLF)
; Also examine the LastErrorText.
ConsoleWrite($oJs.LastErrorText & @CRLF)
Exit
EndIf
ConsoleWrite($oResult.Emit() & @CRLF)
; The describeCar JavaScript function returns nothing.
; Therefore, the result is "undefined".
; {
; "type": "undefined",
; "value": "undefined"
; }
; However, the function emitted text to the console.
$oSbOut = ObjCreate("Chilkat.StringBuilder")
$oJs.ConsoleOutputSb $oSbOut
ConsoleWrite($oSbOut.GetAsString() & @CRLF)
; Output:
; This is a 2022 Toyota Corolla.
; -----------------------------------------------------------
; Note: If the object argument is simple, this is an alternative
; and simpler way of creating the funcCall:
$oFuncCall.Clear
$oFuncCall.UpdateString("name","describeCar")
$oFuncCall.UpdateString("args[0].make","Toyota")
$oFuncCall.UpdateString("args[0].model","Corolla")
$oFuncCall.UpdateInt("args[0].year",2022)
ConsoleWrite($oFuncCall.Emit() & @CRLF)