我正在尝试完全在 C 中构建 JS 对象,类似于以下JS:
var _a = function(p){
this.p = p;
}
_a.prototype.myFunction= function(){ ...; }
var _b = function(){
this.sub = new _a(p);
}
exports.A = A;
exports.B = B;
在 NodeJS 模块中使用它的事实很重要,因为 A 和 B 都不是全局可访问的。
为此,我在C中编写了以下模式:
duk_ret_t _js_a_dtor(duk_context *ctx) {
}
duk_ret_t _js_a_ctor(duk_context *ctx) {
if (!duk_is_constructor_call(ctx)) {
return DUK_RET_TYPE_ERROR;
}
// Push special this binding to the function being constructed
duk_push_this(ctx);
// Store the function destructor
duk_push_c_function(ctx, _js_a_dtor, 0);
duk_set_finalizer(ctx, -2);
return 0;
}
duk_ret_t _js_a_myFunction(duk_context *ctx) {
...
}
static const duk_function_list_entry _js_a_funcs[] = {
{ "", _js_a_myFunction, 0 },
{ NULL, NULL, 0 }
};
duk_ret_t _js_b_dtor(duk_context *ctx) {
}
duk_ret_t _js_b_ctor(duk_context *ctx) {
if (!duk_is_constructor_call(ctx)) {
return DUK_RET_TYPE_ERROR;
}
// Push special this binding to the function being constructed
duk_push_this(ctx);
duk_push_c_function(ctx, _js_a_ctor, 0);
duk_new(ctx,0);
duk_put_prop_string(ctx,"sub");
// Store the function destructor
duk_push_c_function(ctx, _js_b_dtor, 0);
duk_set_finalizer(ctx, -2);
return 0;
}
void duk_init_class(duk_context *ctx, void * ctor, int paramsCount, duk_function_list_entry * func, char * className)
{
// Create object function
duk_push_c_function(ctx, ctor, paramsCount); // [{exports},{ctor}]
// Create a prototype with all functions
duk_push_object(ctx); // [{exports}, { ctor }, {}]
duk_put_function_list(ctx, -1, func); // [{exports}, { ctor }, {}]
duk_put_prop_string(ctx, -2, DUK_PROTOTYPE_NAME); // [{exports}, { ctor }]
// Now store the object function
duk_put_prop_string(ctx, -2, className); // [{exports}]
}
但正如我所怀疑的那样,在调用 duk_new 时没有正确设置 a 的原型,并且任何尝试在JS中使用失败的函数
var m = require('mymodule');
var a = new m.A(); // working
a.myFunction(); // working
var b = new m.B(); // working
b.sub ; // defined
b.sub.myFunction(); // failed while myFunction is undefined..
关于如何解决这个问题的任何想法?我已经知道我可以将构造函数放在全局中,但我想是否有另一种直接的替代方法可以将原型与 c 函数绑定......
问候。