我已经设法将Spidermonkey集成到Linux上的C服务器端应用程序中。 试图从javascript创建一个对象:
var obj = new MyObject();
obj.foo()
给出以下错误:
[error] 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;
}
答案 0 :(得分: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;
}