I have a script which does something like this:
var context = {}
vm.runInNewContext("var someFunc = function() {}", context);
console.log(typeof context.someFunc); //function
console.log(context.someFunc instanceof Function); //false
I do understand why the 4th line returns false: inside the new context there is a new Function
object, which is not equal to the Function
object in the outer context. Therefore, context.someFunc
is not an instance of that outer Function
object.
However, the context.someFunc
function is used by a third-party library which uses instanceof Function
. Since context.someFunc
is a function, but not an instance of the Function
in that context, the third party won't treat it as a function while it should and therefore it crashes. I tried using the following context:
var context = {
"Function" : Function
}
but that didn't resolve my problem either.
Perhaps using var someFunc = new Function(arg, body)
will work (haven't tested it), however I do not have full control of the code passed to vm.runInNewContext
and therefore I can't use that solution either.
How can I let context.someFunc instanceof Function
return true outside of the context?
It's not possible. Use same context in you have no control over thirdparty module. When I've run into similar problem, first i've tried to fix thirdparty module and submit pull request with explanation what was wrong, then I give up and switched to eval in new Function()
instead of running in new context, which fits better with my needs.