使用JavaScript的eval()和多个依赖函数

时间:2017-02-17 23:18:50

标签: javascript eval

如何将动态依赖项加载到$interval(function() { $scope.detail = 'call your getData service here'; }, 1000); ClientsApp.controller("DbController",['$scope','$http', $interval, function($scope,$http,$interval){ ... } 调用中? (如果可能的话)

我正在尝试使用多个函数调用eval(),但我似乎无法让它工作。即:

eval()

理想情况下,我想要的是:

function foo() {
    return bar;
}

function foo2() {
    return foo();
}

但我一直收到错误eval(" (function() { function foo() { return bar; } return foo(); }()) ");

我知道如果在我的页面的html中定义foo is not defined,那么我可以使用foo()编写一个基本上为eval()的函数并获得我想要的结果:< / p>

foo2()

但我希望能够更改这两个功能,但仍然可以调用始终引用eval(" (function() { return foo(); }()) "); 的{​​{1}}。这可能吗?我有什么方法可以让这个工作?

4 个答案:

答案 0 :(得分:2)

尝试将其输入textarea:

func

然后hello将引用func == hellofunc)。然后,您可以使用hello来测试测试用例,例如var ta = document.getElementById("code"); function run() { var code = "(function() { return " + ta.value + "; })()"; // code that will return a reference to the function typed by the user var func = eval(code); // func will be the function the user typed in the textarea func("me"); // you can call it like you want }

<textarea id="code"></textarea>
<button onclick="run()">Run</button>
threadIdx.x

答案 1 :(得分:0)

是的,这是可能的,只需确保您的eval ed代码用新声明覆盖原始函数,通常在全局范围内。

答案 2 :(得分:0)

尝试使用语法 var foo = function(){}而不是你的eval中的函数foo(){},我不知道你如何使多行js字符串不存在,而是一个“;” beetween for eval

答案 3 :(得分:0)

我知道这很老了,但是我找到了一种方法。您必须在每行的末尾加上\并转义引号:

var canvas = document.createElement('canvas')
canvas.id = 'dailyTotalUsersCreated';
canvas.setAttribute('class', `bar dailyChart`)
var container = document.querySelector(`#daily`)
container.appendChild(canvas)
eval(` \
    var ${canvas.id} = new Chart('${canvas.id}', { \
        type: 'bar', \
        data: { \
            labels: [${lastSevenDays.map(obj => `"${new Date(obj.Date).toDateString()}"`)}], \
            datasets: [
                { \
                    label: 'Total Voice Users Created', \
                    data: [${lastSevenDays.map(obj => `${obj.Values.filter(obj => { return obj.Name === "Users Created" }).map(obj => totalUsersCreated - obj.Value)}`)}], \
                    backgroundColor: ['#3e95cd','#8e5ea2','#3cba9f','#e8c3b9','#c45850','#facb48','#384d3f','#247BA0','#F3FFBD','#FF1654'], \
                } \
            ] \
        }, \
        options: { \
            plugins: { \
                datalabels: { \
                    labels: { \
                        title: { \
                            color: 'black' \
                        } \
                    } \
                } \
            }, \
            scales: { \
                yAxes: [{
                    stacked: false,
                    gridLines: {
                        display: true,
                        color: "rgba(255,99,132,0.2)"
                    },
                    ticks: {
                        beginAtZero: true
                    }
                }]
            } \
        } \
    }); \
`);
相关问题