gpt4 book ai didi

Javascript:使全局 eval() 的行为类似于 object.eval()

转载 作者:行者123 更新时间:2023-11-29 10:52:39 28 4
gpt4 key购买 nike

好的 - 我有一个非常具体的案例,我需要使用 eval()。在人们告诉我我根本不应该使用 eval() 之前,让我透露一下我知道 eval 的性能问题、安全问题和所有这些问题。我在非常狭窄的情况下使用它。问题是这样的:

我寻找一个函数,它将变量写入传递给它的任何范围,允许这样的代码:

function mysteriousFunction(ctx) {
//do something mysterious in here to write
//"var myString = 'Oh, I'm afraid the deflector shield will be
//quite operational when your friends arrive.';"
}

mysteriousFunction(this);
alert(myString);

我已经尝试使用全局 eval() 来执行此操作,使用闭包、“with”关键字等伪造执行上下文。我无法让它工作。我发现唯一有用的是:

function mysteriousFunction(ctx) {
ctx.eval("var myString = 'Our cruisers cant repel firepower of that magnitude!';");
}

mysteriousFunction(this);
alert(myString); //alerts 'Our cruisers cant repel firepower of that magnitude!'

但是,上述解决方案需要 object.eval() 函数,该函数已被弃用。它有效,但它让我紧张。有人愿意尝试一下吗?感谢您的宝贵时间!

最佳答案

你可以这样说:

function mysteriousFunction(ctx) {
ctx.myString = "[value here]";
}

mysteriousFunction(this);
alert(myString); // catch here: if you're using it in a anonymous function, you need to refer to as this.myString (see comments)

演示:http://jsfiddle.net/mrchief/HfFKJ/

你也可以这样重构它:

function mysteriousFunction() {
this.myString = "[value here]"; // we'll change the meaning of this when we call the function
}

然后用这样的不同上下文调用(双关语)你的函数:

var ctx = {};
mysteriousFunction.call(ctx);
alert(ctx.myString);

mysteriousFunction.call(this);
alert(myString);

演示:http://jsfiddle.net/mrchief/HfFKJ/4/

关于Javascript:使全局 eval() 的行为类似于 object.eval(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7194926/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com