Augmenting the [[Scope]] Chain
JavaScript performance comparison
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.
| Test | Ops/sec | |
|---|---|---|
Using a Closure |
|
pending… |
Using a with Statement |
|
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:
- Revision 1: published by Ryan Fitzer
- Revision 4: published
0 comments