[quickjs-devel] Defining a New Class

  • From: JM <jeevhi@xxxxxxxxx>
  • To: quickjs-devel@xxxxxxxxxxxxx
  • Date: Wed, 22 Jan 2020 08:38:44 +0530

I am trying to define a new class in a global scope without using modules
and importing it (the way it is done in std class).

I have been following code in "js_std_init" to define my own class except
that I have not used JS_SetModuleExportas since I am not defining any
modules.  Below is the code

#define TEMPLATE_CLASS_NAME "Template"
static JSClassDef template_class = {
        .class_name = TEMPLATE_CLASS_NAME,
        .finalizer = template_finalizer,
};

void template_mod_init(JSContext *ctx) {

        JSValue proto, obj;

        JS_NewClassID(&template_class_id);
        JS_NewClass(JS_GetRuntime(ctx), template_class_id, &template_class);
        proto = JS_NewObject(ctx);
        JS_SetPropertyFunctionList(ctx, proto, template_proto_funcs,
countof(template_proto_funcs));
        JS_SetClassProto(ctx, template_class_id, proto);

        obj = JS_NewCFunction2(ctx, template_constructor,
TEMPLATE_CLASS_NAME, 1, JS_CFUNC_constructor, 0);
        JS_SetPropertyFunctionList(ctx, obj, template_class_funcs,
countof(template_class_funcs));
        //JS_SetModuleExport(ctx, m, TEMPLATE_CLASS_NAME, obj);
}

I am calling template_mod_init(ctx) after creating a new context.

However, the Template class is not visible in javascript. I am getting
following error for new Template();

ReferenceError: Template is not defined
    at <eval> (./template_test.js:1)

I assume that it needs to be exported. Any idea what functions to be used
or any other insight.

Other related posts: