0

我已经设法将 Spidermonkey 集成到我在 Linux 上的 C 服务器端应用程序中。尝试从 javascript 创建一个对象:

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

给出以下错误:

[错误] test.js:22:TypeError: obj.foo 不是函数

我可能遗漏了一些东西......这是 MyObject 的定义方式:

//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;

}
4

1 回答 1

1

我能够找到一些较旧的示例,其中包括:

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

在构造函数中。

它起到了魅力的作用。

//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;

}
于 2012-03-05T07:16:16.880 回答