Skip to content

Commit 80c01e0

Browse files
committed
add callFunction example
1 parent 6a05948 commit 80c01e0

File tree

1 file changed

+30
-2
lines changed

1 file changed

+30
-2
lines changed

packages/quickjs-emscripten-core/src/context.ts

Lines changed: 30 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1035,7 +1035,8 @@ export class QuickJSContext
10351035
// Evaluation ---------------------------------------------------------------
10361036

10371037
/**
1038-
* [`func.call(thisVal, ...args)`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call).
1038+
* [`func.call(thisVal, ...args)`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call) or
1039+
* [`func.apply(thisVal, args)`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply).
10391040
* Call a JSValue as a function.
10401041
*
10411042
* See {@link unwrapResult}, which will throw if the function returned an error, or
@@ -1046,13 +1047,40 @@ export class QuickJSContext
10461047
* @returns A result. If the function threw synchronously, `result.error` be a
10471048
* handle to the exception. Otherwise `result.value` will be a handle to the
10481049
* value.
1050+
*
1051+
* Example:
1052+
*
1053+
* ```typescript
1054+
* using parseIntHandle = context.getProp(global, "parseInt")
1055+
* using stringHandle = context.newString("42")
1056+
* using resultHandle = context.callFunction(parseIntHandle, context.undefined, stringHandle).unwrap()
1057+
* console.log(context.dump(resultHandle)) // 42
1058+
* ```
10491059
*/
1060+
callFunction(
1061+
func: QuickJSHandle,
1062+
thisVal: QuickJSHandle,
1063+
args?: QuickJSHandle[],
1064+
): ContextResult<QuickJSHandle>
10501065
callFunction(
10511066
func: QuickJSHandle,
10521067
thisVal: QuickJSHandle,
10531068
...args: QuickJSHandle[]
1069+
): ContextResult<QuickJSHandle>
1070+
callFunction(
1071+
func: QuickJSHandle,
1072+
thisVal: QuickJSHandle,
1073+
...restArgs: Array<QuickJSHandle | QuickJSHandle[] | undefined>
10541074
): ContextResult<QuickJSHandle> {
10551075
this.runtime.assertOwned(func)
1076+
let args
1077+
const firstArg = restArgs[0]
1078+
if (firstArg === undefined || Array.isArray(firstArg)) {
1079+
args = firstArg ?? []
1080+
} else {
1081+
args = restArgs as QuickJSHandle[]
1082+
}
1083+
10561084
const resultPtr = this.memory
10571085
.toPointerArray(args)
10581086
.consume((argsArrayPtr) =>
@@ -1089,7 +1117,7 @@ export class QuickJSContext
10891117
args: QuickJSHandle[] = [],
10901118
): ContextResult<QuickJSHandle> {
10911119
return this.getProp(thisHandle, key).consume((func) =>
1092-
this.callFunction(func, thisHandle, ...args),
1120+
this.callFunction(func, thisHandle, args),
10931121
)
10941122
}
10951123

0 commit comments

Comments
 (0)