Question

I've managed to integrate Spidermonkey into my C server side application on Linux. Trying to create an object from javascript:

var obj = new MyObject();
obj.foo()

gives the following Error:

[error] test.js:22:TypeError: obj.foo is not a function

I'm probably missing something...Here is how MyObject defined:

//Class definition
static JSClass myobject_class = {
    "MyObject", JSCLASS_HAS_PRIVATE,
        JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_StrictPropertyStub,
        JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, JS_FinalizeStub,
        JSCLASS_NO_OPTIONAL_MEMBERS
};


//Methods
static JSFunctionSpec myobject_funcs[] = {
    JS_FS("foo", JS_foo, 0, 0),
};


//Static methods
static JSFunctionSpec myobject_funcs_static[] = {
    JS_FS_END
};



//foo method
JSBool JS_foo(JSContext *cx, uintN argc, jsval *vpn) {

    return JS_TRUE;
}


//Constructor
JSBool JS_myobject_ctor(JSContext *cx, uintN argc, jsval *vpn) {

    JSObject *obj = JS_NewObjectForConstructor(cx, vpn);
    JS_DefineFunctions(cx,obj,myobject_funcs);


    return JS_TRUE;

}

//Init context
JSContext *  context_init(size_t size,void* privateData) {
    /* Create a context. */
    jsContext = JS_NewContext(jsRuntime, 8192);
    if (jsContext == NULL) return NULL;
    .....
    .....
    .....  
    //myobject init
    JSObject *my = JS_InitClass(jsContext, global, NULL, &myobject_class, JS_myobject_ctor, 0, NULL, NULL, NULL, myobject_funcs_static);
    JS_DefineFunctions(jsContext, my, myobject_funcs);

    return jsContext;

}
Was it helpful?

Solution

I was able to find some older example that included:

JS_SET_RVAL(cx, vpn, OBJECT_TO_JSVAL(obj));

in the constructor.

It worked as a charm.

//Constructor
JSBool JS_myobject_ctor(JSContext *cx, uintN argc, jsval *vpn) {

    JSObject *obj = JS_NewObjectForConstructor(cx, vpn);
    JS_DefineFunctions(cx,obj,myobject_funcs);


    JS_SET_RVAL(cx, vpn, OBJECT_TO_JSVAL(obj));

    return JS_TRUE;

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top