Use a function inside "windows.onload" outside of curly braces?

Viewed 37

is there a way to use a function written inside of windows.onload outside it's curly?

I mean to make it callable somehow without the need to rewrite the entire same function outside?

For instance:

   window.onload = function () {
     async function doSomething() {
     // do something...
     }
   doSomething(); // I want to use this function outside windows.onload "without" rewriting the exact same function outside.
   }
   // make doSomething() callable here somehow. 

Is is possible with Vanilla Javascript or will I need to rewrite the same function again?

2 Answers

No.

You could assign doSomething to a global variable inside onload but it would be assigned too late to use it where you want to.

If you want doSomething to be a global, then define it as one in the first place. Don't scope it to the onload function.

I don't think this is a good idea...

window.onload = function (event, refHook) {
  if (!event && refHook) {
    refHook.doSomething = doSomething;
    return;
  }
  async function doSomething() {}
};
const refHook = {};
window.onload(null, refHook);
refHook.doSomething();
Related