Augmenting the [[Scope]] Chain

JavaScript performance comparison

Test case created by Ryan Fitzer

Info

A method to inject a named variable into the scope of a function.

~ proxyScope1( vars, fn ) ~

Augments the local scope by creating a series of var statements in a closure, which is returned as a new Function.

~ proxyScope2( fn ) ~

Augments the local scope by returning a new Function that executes the function inside a with statement (must be executed with apply to create the context). Original from Ben Nadel: http://www.bennadel.com/blog/1929-Using-The-WITH-Keyword-With-Javascript-s-Function-Constructor.htm

Preparation code

<script>
  function generic() {
      // console.log('a =', a);
  };
 
  function proxyScope1( vars, fn ) {
     
      var name,
          tmplClosure,
          augVars = '';
         
      for ( name in vars )
          augVars += 'var ' + name + ' = ' + ( typeof vars[ name ] == 'string' ? '"' + vars[ name ] + '"' : vars[ name ]) + ';';
             
      tmplClosure = 'return ( function() { ' + augVars + '; return ' + fn + ' } )();';
     
      return ( Function( tmplClosure ) )();
     
  };
 
  function proxyScope2( fn ) {
     
      var newFn = 'with ( this ) return ' + fn + '()';
     
      return ( Function( newFn ) );
     
  };
</script>

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
Using a Closure
proxyScope1( { a: 'test' }, generic )();
pending…
Using a with Statement
proxyScope2( generic ).apply( { a: 'test' } );
pending…

Compare results of other browsers

Revisions

You can edit these tests or add even more tests to this page by appending /edit to the URL. Here’s a list of current revisions for this page:

0 comments

Add a comment