在特定的上下文中调用eval() [英] calling eval() in particular context

查看:103
本文介绍了在特定的上下文中调用eval()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下javaScriptclass:

I have following javaScript "class":

A = (function() {
   a = function() { eval(...) };
   A.prototype.b = function(arg1, arg2) { /* do something... */};
})();

现在让我们假设在eval()中我传递的字符串包含调用带有一些参数的表达式:

Now let's assume that in eval() I'm passing string that contains expression calling b with some arguments:

 b("foo", "bar")

然后我得到b未定义的错误。所以我的问题是:如何在A类语境中调用eval?

But then I get error that b is not defined. So my question is: how to call eval in context of class A?

推荐答案

其实你可以通过函数实现抽象:

Actually you can accomplish this with an abstraction via a function:

var context = { a: 1, b: 2, c: 3 };

function example() {
    console.log(this);
}

function evalInContext() {
    console.log(this);        //# .logs `{ a: 1, b: 2, c: 3 }`
    eval("example()");        //# .logs `{ a: 1, b: 2, c: 3 }` inside example()
}

evalInContext.call(context);

所以你调用带有<的函数code> context 你想要并在该函数中运行 eval

So you call the function with the context you want and run eval inside that function.

奇怪的是,这似乎在本地工作,但不适用于 Plunkr

Oddly, this seems to be working for me locally but not on Plunkr!?

对于简洁(可以说是多汁的)版本,您可以逐字复制到您的代码中,使用:

For a succinct (and arguably succulent ;) version you can copy verbatim into your code, use this:

function evalInContext(js, context) {
    //# Return the results of the in-line anonymous function we .call with the passed context
    return function() { return eval(js); }.call(context);
}

这篇关于在特定的上下文中调用eval()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆