0

我正在尝试完全在 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 函数绑定......

问候。

4

1 回答 1

1

Duktape/C 函数默认没有.prototype属性,因此当它们作为构造函数调用时,创建的实例将继承自 Object.prototype。要改变它,你可以简单地设置.prototype函数的属性。

因此,如果我理解正确,在您的情况下,您可以执行以下操作:

/* Build prototype object, here: { myFunction: ... } */
duk_push_object(ctx);
duk_push_c_function(ctx, _js_a_myFunction, ...);
duk_put_prop_string(ctx, -2, "myFunction");

/* Set A.prototype. */
duk_put_prop_string(ctx, idx_for_A_ctor, "prototype");

如果使用 duk_put_function_list(),则需要从目标对象中读取构造函数值,以便设置其.prototype.

于 2017-04-26T20:01:38.827 回答