将类函数暴露给使用 JavaScript 中的字符串创建的函数?

问题描述

我需要运行一堆保存在文本中的脚本。我需要在运行时将它们转换为 JavaScript,它可能会调用该类中的某些函数获取一些数据,如下所示。基本上,我需要将类的函数公开给在同一类的函数之一中运行的那些脚本。只要我不调用 randomNumbers() 函数并对一些数字进行硬编码,它就可以正常工作。 我将不胜感激对此的任何反馈。 谢谢,

   var config = {
    minX: 1,maxX: 10,get randomIntFromInterval() {
        return (() =>
            Math.floor(Math.random() * (this.maxX - this.minX + 1) + this.minX)).bind(
                config
            );
    },};
        
        
        export const executeFns = () => {
            let edit = `
            let a = randomIntFromInterval();
            let b = randomIntFromInterval();
            if (a> b) {
            console.log('a is bigger than b')
            } else if (b>a) {
            console.log('b is bigger than a')
            }
            console.log('a',a );
            console.log('b',b )`;
        
            var f4 = NamedFunction('fancyname',[],edit,config);
            f4();
        };
        
            export function NamedFunction(name,args,body,scope,values) {
                if (typeof args == 'string') {
                    values = scope;
                    scope = body;
                    body = args;
                    args = [];
                }
            
                if (!Array.isArray(scope) || !Array.isArray(values)) {
                    if (typeof scope == 'object') {
                        var keys = Object.keys(scope);
                        values = keys.map(function (p) {
                            return scope[p];
                        });
                        scope = keys;
                    } else {
                        values = [];
                        scope = [];
                    }
                }
                return Function(
                    scope,'function ' +
                        name +
                        '(' +
                        args.join(',') +
                        ') {\n' +
                        body +
                        '\n}\nreturn ' +
                        name +
                        ';'
                ).apply(null,values);
            }

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)