JSAPI Cookbook

  • Revision slug: SpiderMonkey/JSAPI_Cookbook
  • Revision title: JSAPI Cookbook
  • Revision id: 73994
  • Created:
  • Creator: Jorend
  • Is current revision? No
  • Comment /* Calling functions */ layout mostly

Revision Content

This article shows the JSAPI equivalent for a tiny handful of common JavaScript idioms.

// JavaScript
var x = [];
// JSAPI
JSObject *x = JS_NewArrayObject(cx, 0, NULL);
if (x == NULL)
    return JS_FALSE;

Calling a global JS function

// JavaScript
var r = foo();  // where f is a global function
/* JSAPI
 *
 * Suppose the script defines a global JavaScript
 * function foo() and we want to call it from C.
 */
jsval r;
if (!JS_CallFunctionName(cx, JS_GetGlobalObject(cx), "foo", 0, NULL, &r))
   return JS_FALSE;

Calling a JS function via a local variable

// JavaScript
var r = f();  // where f is a local variable
/* JSAPI
 *
 * Suppose f is a local C variable of type jsval.
 */

/* First, convert it to JSFunction*. */
JSFunction *f_fun = JS_ValueToFunction(cx, f);
if (ffun == NULL)
    return JS_FALSE;

/* Then call it. */
jsval r;
if (!JS_CallFunction(cx, JS_NULL, f_fun, 0, NULL, &r)
    return JS_FALSE;

Revision Source

<p>This article shows the JSAPI equivalent for a tiny handful of common JavaScript idioms.
</p>
<pre class="eval">// JavaScript
var x = [];
</pre>
<pre class="eval">// JSAPI
JSObject *x = <a href="en/JS_NewArrayObject">JS_NewArrayObject</a>(cx, 0, NULL);
if (x == NULL)
    return JS_FALSE;
</pre>
<h4 name="Calling_a_global_JS_function"> Calling a global JS function </h4>
<pre class="eval">// <b>JavaScript</b>
var r = foo();  // where f is a global function
</pre>
<pre class="eval">/* <b>JSAPI</b>
 *
 * Suppose the script defines a global JavaScript
 * function foo() and we want to call it from C.
 */
jsval r;
if (!<a href="en/JS_CallFunctionName">JS_CallFunctionName</a>(cx, <a href="en/JS_GetGlobalObject">JS_GetGlobalObject</a>(cx), "foo", 0, NULL, &amp;r))
   return JS_FALSE;
</pre>
<h4 name="Calling_a_JS_function_via_a_local_variable"> Calling a JS function via a local variable </h4>
<pre class="eval">// <b>JavaScript</b>
var r = f();  // where f is a local variable
</pre>
<pre class="eval">/* <b>JSAPI</b>
 *
 * Suppose f is a local C variable of type jsval.
 */

/* First, convert it to JSFunction*. */
JSFunction *f_fun = <a href="en/JS_ValueToFunction">JS_ValueToFunction</a>(cx, f);
if (ffun == NULL)
    return JS_FALSE;

/* Then call it. */
jsval r;
if (!<a href="en/JS_CallFunction">JS_CallFunction</a>(cx, <a href="en/JS_NULL">JS_NULL</a>, f_fun, 0, NULL, &amp;r)
    return JS_FALSE;
</pre>
Revert to this revision