Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 220
Alex Avatar asked Jul 26 '26 05:07

Alex


2 Answers

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/

like image 150
Mrchief Avatar answered Jul 27 '26 20:07

Mrchief


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);
like image 35
Joe Avatar answered Jul 27 '26 20:07

Joe