Created
April 25, 2012 19:35
-
-
Save ralphholzmann/2492633 to your computer and use it in GitHub Desktop.
JavaScript with-like function
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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 theobj
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.