简体   繁体   English

用Javascript创建一个可以访问局部变量的类

[英]Create a class in Javascript that can access local variables

I'm working on a debugger that injects code into already existing code. 我正在开发一个将代码注入到现有代码中的调试器。 Which then use eval() to log and run it. 然后使用eval()记录并运行它。

However eval() seems to work in only its existing scope. 但是,eval()似乎仅在其现有范围内起作用。 To overcome this I tried to add a class that i recreated in each local scope. 为了克服这个问题,我尝试添加一个在每个本地范围内重新创建的类。 But it doesnt work. 但它不起作用。

I've added code to ilustrate my problem. 我添加了代码来说明我的问题。 The first alert works as expected, I'm assuming that it is because MyClass is created in the same scope. 第一个警报按预期工作,我假设这是因为MyClass是在同一范围内创建的。

The second alert still display b as 10 even though I've set b in local scope to 20 inside the TestC function. 即使我在TestC函数中将本地范围内的b设置为20,第二个警报仍将b显示为10。 And the last alert doesn't work at all eval() returns in console "Uncaught ReferenceError: c is not defined". 而且最后一个警报根本不起作用,控制台中的eval()返回“未捕获的ReferenceError:未定义c”。

If I add the whole MyClass inside each function and the assign it, then it works, but that doesn't feel like an elegant solution. 如果我在每个函数中添加整个MyClass并对其进行分配,则它可以工作,但是那感觉并不好。 And can add 1000's of lines of code to a project. 并且可以向项目添加1000行代码。

http://jsfiddle.net/ekim/zryj3taq/2/ http://jsfiddle.net/ekim/zryj3taq/2/

var MyClass = function()
{
    this.MyAlert = function(codex)
    {
        eval(codex);
    }
}

var b = 10;
var MyOne = new MyClass();
MyOne.MyAlert("alert(b);");

function TestC()
{
    var b = 20;
    var MyOne2 = new MyClass();
    MyOne2.MyAlert("alert(b);");

    var c = 20;
    var MyOne2 = new MyClass();
    MyOne2.MyAlert("alert(c);");
}


TestC();

You can use new Function(\\[arg1\\[, arg2\\[, ...argN\\]\\],\\] functionBody) 您可以使用new Function(\\[arg1\\[, arg2\\[, ...argN\\]\\],\\] functionBody)

 (function(){ var str = "return (A+B)*C"; var myFunc = new Function("A","B","C", str); var result = myFunc(2,3,4); console.log(result); }()); /* Example with function */ (function(){ var fncDouble = function (X) { return X*2; } var str = "return F(A)+B"; var myFunc = new Function("F","A","B", str); var result = myFunc(fncDouble,3,1); console.log(result); }()); 

据我所知,没有简单的解决方案,因为eval()函数只是创建一个新的单独的编译器。

试试这个: MyOne2.MyAlert.call(this, "alert(b)");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM