Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Distinguishing local eval from global eval

Tags:

javascript

Please consider the two snippets of code (the first prints "Local eval", the second prints "Global eval"):

(function f() { 
    var x;
    try {
        eval("x");
        console.log('Local eval');
    }
    catch (e) {
        console.log('Global eval');
    }
}())

and

var globalEval = eval;
(function f() { 
    var x;
    try {
        globalEval("x");
        console.log('Local eval');
    }
    catch (e) {
        console.log('Global eval');
    }
}())

It turns out that even though globalEval === eval evaluates to true, globalEval and eval behave differently because they have different names. (An eval can only be local if it is precisely written eval.)

How can I distinguish to two evals? Is there are a way to extract variable labels to infer behaviour?

like image 816
Randomblue Avatar asked Feb 05 '12 15:02

Randomblue


1 Answers

Interesting. But since you're in control of where/when your reference to eval is defined, you get to say how to distinguish them. For example have an object that has the "function pointer" AND something to indicate the scope - if you define it, you know where you stand.

I.e. myEvaluator.scope would tell you info about where the eval scope was captuerd, and myEvaluator.eval could be used to evaluate.

like image 75
Kieren Johnstone Avatar answered Oct 02 '22 20:10

Kieren Johnstone