Sample code for 30+ languages & platforms
Xbase++ Requires Chilkat v11.4.0+

Call a JavaScript Function Returning an Object

See more JavaScript Examples

Demonstrates how to call a JavaScript function that returns an object.

Chilkat Xbase++ Downloads

Xbase++
LOCAL nSuccess
LOCAL oSbScript
LOCAL oJs
LOCAL oResult
LOCAL oFuncCall

nSuccess := 0

//  This is the JavaScript function we'll call:

//  function getSettings() {
//      return {
//          theme: "dark",
//          notifications: true,
//          version: 1.0
//      };
//  }

oSbScript := CreateObject("Chilkat.StringBuilder")
oSbScript:Append("function getSettings() {")
oSbScript:Append("    return {")
oSbScript:Append('        theme: "dark",')
oSbScript:Append("        notifications: true,")
oSbScript:Append("        version: 1.0")
oSbScript:Append("    };")
oSbScript:Append("}")

oJs := CreateObject("Chilkat.Js")

oResult := CreateObject("Chilkat.JsonObject")
oResult:EmitCompact := 0

//  Call Eval to add the function to the context's global object
nSuccess := oJs:Eval(oSbScript, oResult)
IF (nSuccess == 0)
    //  Examine the result for an exception.
    ? oResult:Emit()

    //  Also examine the LastErrorText.
    ? oJs:LastErrorText
    oSbScript:destroy()
    oJs:destroy()
    oResult:destroy()
    RETURN
ENDIF

//  ------------------------------------------------------------------------------
//  Call the function getSettings()

oFuncCall := CreateObject("Chilkat.JsonObject")

//  Create JSON specifying the function name and arguments
//  The function has no arguments, so we only specify the name.

//  {
//    "name": "getSettings",
//  }

oFuncCall:UpdateString("name", "getSettings")

nSuccess := oJs:CallFunction(oFuncCall, oResult)
IF (nSuccess == 0)
    //  Examine the result for an exception.
    ? oResult:Emit()

    //  Also examine the LastErrorText.
    ? oJs:LastErrorText
    oSbScript:destroy()
    oJs:destroy()
    oResult:destroy()
    oFuncCall:destroy()
    RETURN
ENDIF

? oResult:Emit()

//  Output:
//  {
//    "type": "object",
//    "value": {
//      "theme": "dark",
//      "notifications": true,
//      "version": 1
//    }
//  }

//  Examine the object's members
? "theme: " + oResult:StringOf("value.theme")
? "notifications: " + Str(oResult:BoolOf("value.notifications"))
? "version: " + Str(oResult:IntOf("value.version"))

//  Output:
//  theme: dark
//  notifications: True
//  version: 1

oSbScript:destroy()
oJs:destroy()
oResult:destroy()
oFuncCall:destroy()