Understanding from just the title can be tricky. Let me provide an example. I need a function to automatically refer to a variable that is "injected", like this:
function abc() {
console.log(myVariable);
}
I attempted to achieve this with:
with({myVariable: "value"}) { abc() }
However, this only works if abc is declared within the with block, as shown below:
with({myVariable: "value"}) {
function abc() {
console.log(myVariable);
}
abc(); // This will work
}
The last scenario works, but can we mimic the with statement or should developers be required to declare their function calls in a with statement?
The desired call looks like this:
doSomething({myVariable: "value"}, function() {
console.log(myVariable);
});
Although passing it as a single parameter object is possible, that's not the goal here:
doSomething({myVariable: "value"}, function(M) {
console.log(M.myVariable);
});
Furthermore, the aim is to avoid using eval:
with({myVariable: "value"}) {
eval(abc.toString())(); // Will also work
}
Is it feasible in JavaScript beyond using eval?