In browsers, setTimeout
lives in window
or self
, which are equal. In web workers, only self
is present. On Node.js, global
represents the global context and setTimeout
exists within it. And there are more than just these two javascript platforms.
I need to call a setTimeout
function but I have an arbitrary number of arguments to pass to it - 3rd and following arguments are passed to the callback. In browser of web worker, this works:
setTimeout.apply(self, [alert, 666, "Hello"])
Node.js console accepts this:
setTimeout.apply(global, [console.log, 500, "Hello."])
So what's the general answer? How to use apply on function with unknown or variable this
scope without breaking that scope?
Edit to clarify: because it appears one solution might be to get access to global object using some procedure that detects it, I want to clarify that I was hoping to fetch this
scope from the function I'm gonna call. Something like inversion of .bind
- get the this
scope and apply it, so that it works even on non global functions. The idea:
setTimeout.apply(setTimeout.getThisObject(), [alert, 666, "Hello"])