Skip to content

Instantly share code, notes, and snippets.

@ralphholzmann
Created April 25, 2012 19:35
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save ralphholzmann/2492633 to your computer and use it in GitHub Desktop.
JavaScript with-like function
var obj = {
"ralph" : 1,
"jon" : 2,
"alex" : 3
};
function _with( fn, data ) {
var keys = Object.keys( data ),
values = keys.map(function( key ) {
return data[key];
});
new Function("(function(" + keys.join() + ") { return (" + fn.toString() + ")() }).apply(this, arguments)").apply( this, values );
}
_with(function() {
console.log( ralph, jon, alex ); // 1, 2, 3
}, obj);
@benvinegar
Copy link

I think this has difficulty with closures. i.e. your generated function can't access any closure-scope variables from the input function.

@ralphholzmann
Copy link
Author

That's a great point @benvinegar. There are also some other inconsistencies, such as, mutating properties made available by the _with function won't modify the obj passed in.

This was concocted as an alternative to using with for a templating library, which, for that use case, these inconsistencies may be advantageous, or moot.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment