JavascriptCore中扩展自定义函数

JavaScriptCore中预定义了不少函数,可以直接使用,也可以扩展子定义的函数,我们扩展的自定义函数肯定是在全局访问空间,那么

需要继承JSGlobalObject自定义自己的全局访问空间,或者干脆直接修改也可以

具体来说就是在构造函数中添加下面一句:

putDirectFunction(globalExec(), new (globalExec()) NativeFunctionWrapper(globalExec(), prototypeFunctionStructure(), 1, Identifier(globalExec(), "print"), functionPrint));

这样就有一个print函数可以访问了 ,而函数的实现则是functionPrint,

定义如下:

JSValue JSC_HOST_CALL functionPrint(ExecState* exec, JSObject*, JSValue, const ArgList& args)
{
    for (unsigned i = 0; i < args.size(); ++i) {
        if (i != 0)
            putchar(' ');
        printf("%s", args.at(i).toString(exec).UTF8String().c_str());
    }
    putchar('\n');
    fflush(stdout);
    return jsUndefined();
}

前面的我们都不用考虑,主要是最后一个args,它里面包含了想要的参数,下面是使用示例:

$ jsc.exe
> print(3)
3
undefined
> print(3,4,5)
3 4 5
undefined
>

原文地址:https://www.cnblogs.com/baizx/p/1797737.html