Skip to content

Instantly share code, notes, and snippets.

@addywaddy
Created March 16, 2012 12:18
Show Gist options
  • Save addywaddy/2049843 to your computer and use it in GitHub Desktop.
Save addywaddy/2049843 to your computer and use it in GitHub Desktop.
'using' - an alternative to the 'with' statement
function using (obj) {
var _keys = Object.keys || function(obj) {
if (obj !== Object(obj)) {
throw new TypeError('Invalid object');
}
var keys = [];
for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)(obj, key)) {
keys[keys.length] = key;
}
}
return keys;
};
return function(cb) {
var varKeys = _keys(obj);
for (var i = varKeys.length - 1; i >= 0; i--){
var value = obj[varKeys[i]];
if (typeof(value) === 'string') {
value = '\"' + value + '\"';
}
eval('var '+varKeys[i] + '=' + value);
};
eval('(' + cb.toString() + ')')();
}
}
var scopeObject = {
aString: 'Guten Tag',
aNumber: 12,
aFunction: function(strA) {
return function(strB) {
console.log(strA + ' and ' + strB);
}
}
}
// Simple benchmark putting 'using' against 'with'
var codez = [
{
name: "Using",
code: function() {
using(scopeObject)(function() {
console.log(aNumber);
console.log(aString);
aFunction("one")("two");
});
}
},
{
name: "With",
code: function() {
with(scopeObject) {
console.log(aNumber);
console.log(aString);
aFunction("three")("four");
}
}
}
]
for (var i = codez.length - 1; i >= 0; i--){
var start = new Date();
codez[i].code();
console.log(codez[i].name + ": Duration:", new Date() - start);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment