js eval

var variableRe=/^[_0-9a-zA-Z][_0-9a-zA-Z]?$/;
    variableRe.compile(/^[_$a-zA-Z][_$0-9a-zA-Z]*$/);
    var keywords=["if","then"];
    var isValidVariable=function(name){
        return variableRe.test(name) && keywords.indexOf(name)==-1
    }
    Platform.eval = function(exp, scope, context)
    {
        // 计算js表达式
        // exp:要计算的表达式
        // scope:表达式中this的对象
        // context:表达式的上下文,即变量的可取值,如{pi:3.14,inc:function(n){return n+1;}}
        if (Ext.isString(exp))
        {
            var ct = "";
            
            if (Ext.isObject(context))
            {
                Ext.iterate(context, function(k, v)
                {
                    if (isValidVariable(k)) ct += "var " + k + "= context['" + k + "'];"
                });
                exp = ct + "\n" + exp;
            }

            var fn = function()
            {
                var v;
                try
                {
                    v = eval(exp)
                }
                catch (e)
                {};
                return v;
            }

            return fn.call(scope);
        }
    }

猜你喜欢

转载自keren.iteye.com/blog/1999109