Jared Grippe

Function#evalWith

I’ve been exploring ways to avoid having to write with at the top of functions where you want access to methods and attributes without having to write this. or object. all the time and I came up with this:

function evalWith(objects, args, context){
    if (!('length' in objects)) throw new SyntaxError('first argument to evalWith must be an array');
    if (args && !(args instanceof Array)) throw new SyntaxError('second argument to evalWith must be an array');

    var scope = {}; // merge objects into one
    for (var i=0; i < objects.length; i++)
      for (var property in objects[i])
        scope[property] = objects[i][property];
    
    var method = new Function(
      'with(arguments[0]){'+
        'return '+this.toString().replace(/^function (.*?)\(/,'function (')+'.apply(arguments[1],arguments[2]);'+
      '}'
    );
    return method.call(null, scope, context || window, args || []);
  };

more to come…


Comments
blog comments powered by Disqus
To Tumblr, Love Metalab