Restricting eval() to a narrow scope

前端 未结 8 2081
误落风尘
误落风尘 2020-11-27 04:51

I have a javascript file that reads another file which may contain javascript fragments that need to be eval()-ed. The script fragments are supposed to conform to a strict s

相关标签:
8条回答
  • 2020-11-27 05:31

    Similar to the dynamic function wrapping script in a with block approach above, this allows you to add pseudo-globals to the code you want to execute. You can "hide" specific things by adding them to the context.

    function evalInContext(source, context) {
        source = '(function(' + Object.keys(context).join(', ') + ') {' + source + '})';
    
        var compiled = eval(source);
    
        return compiled.apply(context, values());
    
        // you likely don't need this - use underscore, jQuery, etc
        function values() {
            var result = [];
            for (var property in context)
                if (context.hasOwnProperty(property))
                    result.push(context[property]);
            return result;
        }
    }
    

    See http://jsfiddle.net/PRh8t/ for an example. Note that Object.keys is not supported in all browsers.

    0 讨论(0)
  • 2020-11-27 05:31

    You cant limit the scope of eval

    btw see this post

    There may be some other way to accomplish what it is you want accomplish in the grand scheme of things but you cannot limit the scope of eval in any way. You may be able to hide certain variables as pseudo private variables in javascript, but I dont think this is what you're going for.

    0 讨论(0)
提交回复
热议问题