I recently found myself needing to use "with", and hating myself for it. Does anyone know a better way to do this in JavaScript?
// Take an array of context dictionaries, and return a
// function that evaluates a string in those contexts.
// I fully realize how horrible this code is, and that
// it only supports up to ten contexts. I feel terrible
// about it, as I should, but I would feel even worse
// if it were impossible to do this. But isn't there
// a simpler way to do this is JavaScript? Maybe I
// could use __proto__ inheritence, but I was hoping
// to avoid.
function evalInContextsFunction(_contexts) {
var _contextCount = _contexts.length;
if (_contextCount == 0) {
return function evalInContexts(_text) {return eval(_text)};
}
with (_contexts[0] || {}) {
if (_contextCount == 1) {
return function evalInContexts(_text) {return eval(_text)};
}
with (_contexts[1] || {}) {
if (_contextCount == 2) {
return function evalInContexts(_text) {return eval(_text)};
}