开发者

Javascript: making the global eval() behave like object.eval()

开发者 https://www.devze.com 2023-03-30 15:11 出处:网络
Ok- I have a very specific case for which I need to use eval(). Before people tell me that I shouldn\'t be using eval() at all, let me disclose that I\'m aware of eval\'s performance issues, security

Ok- I have a very specific case for which I need to use eval(). Before people tell me that I shouldn't be using eval() at all, let me disclose that I'm aware of eval's performance issues, security issues and all that jazz. I'm using it in a very narrow case. The problem is this:

I seek a function which will write a variable to whatever scope is passed into it, allowing for code like this:

function mysteriousFunction(ctx) {
//do something mysterious in here to write
//"var myString = 'Oh, I'm afraid the deflector shield will be 
//quite operational wh开发者_如何学Goen your friends arrive.';"
}

mysteriousFunction(this);
alert(myString);

I've tried using global eval() to do this, faking the execution context with closures, the 'with' keyword etc. etc. I can't make it work. The only thing I've found that works is:

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!'

However, the above solution requires the object.eval() function, which is deprecated. It works but it makes me nervous. Anyone care to take a crack at this? Thanks for your time!


You can say something like this:

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)

Demo: http://jsfiddle.net/mrchief/HfFKJ/

You can also refactor it like this:

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

And then call (pun intended) your function with different contexts like this:

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

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

Demo: http://jsfiddle.net/mrchief/HfFKJ/4/


jsFiddle

EDIT: As @Mathew so kindly pointed out my code MAKES NO SENSE! So a working example using strings:

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


I'm fairly sure it's impossible to write to the function scope (i.e. simulate var) from another function, without eval.

Note that when you pass this, you're either passing the window, or an object. Neither identifies a function (the scope of a non-global var).

0

精彩评论

暂无评论...
验证码 换一张
取 消