This code works:
it.cb(h => {
console.log(h);
h.ctn();
});
it.cb(new Function(
'h', [
'console.log(h)',
'h.ctn()'
]
.join(';')
));
these two test cases are basically identical. But constructing a string with array like that is cumbersome, and you can't get static analysis. So what I was thinking of doing was something like this:
it.cb(isolated(h => {
console.log(h);
h.ctn();
}));
where isolated is a helper function that looks something like:
const isolated = function(fn){
const str = fn.toString();
const paramNames = getParamNames(str);
return new Function(...paramNames.concat(str));
};
the biggest problem is that Function.prototype.toString()
gives you the whole function. Does anyone know of a good way to just get the function body from the string representation of the function?
Update: PRoberts was asking what the purpose of this is, the purpose is simply:
const foo = 3;
it.cb(isolated(h => {
console.log(foo); // this will throw "ReferenceError: foo is not defined"
h.ctn();
}));