JavaScript with scope, undefined

As part of my template engine, I need to evaluate expressions in JavaScript, for example: "first || second"in the context of some role that serves as the global namespace. Thus, the properties of an object should be considered as global variables.

So far, I came up with this function:

function scopedEval(str, scope) {
   var f = new Function("scope", "with(scope) { return (" + str + "); }");
   return f(scope);  
}

Everything is fine and I can run it as:

var scope = { first:1, second:2 };
var expr1  = "first || second";
alert( scopedEval(expr1,scope) );

he alerts me 1.

The only problem with variables that were not defined in the scope object. It:

var expr2  = "third || first || second";
alert( scopedEval(expr2,scope) );

generates a "variable thirdnot defined" error . But I would like all unknown variables to be resolved before undefined, rather than throwing errors. So, "third || first || second" should again go back to 1.

, JavaScript, - . ?

: http://jsfiddle.net/nCCgT/

+3
3

ECMAScript. Rhino, JDK , , SpiderMonkey catch , .

- ES Harmony, , .

, str () scope :

var toks = str.match(/[A-Za-z_$][\w$]*/g);
for(var i = 0; i < toks.length; ++i) {
    if(!(toks[i] in scope))
        scope[toks[i]] = undefined;
}
+3

, JS, ( ).

: , - JS , . , , , , , . , , .

: " / . ". .

+1

If I understand your question correctly, this should do what you want:

function scopedEval(str, scope) {
   var toCheck = str.split(' || ');
    for(var i = 0; i < toCheck.length; ++i){
        if(scope[toCheck[i]])
            return scope[toCheck[i]];
    }
}

You may need to check a little better here and there, but the method works on your fiddle :) http://jsfiddle.net/nCCgT/1/

0
source

All Articles