0

OK I have looked for a solution to this and have failed, if i have missed a post here please point me to it.

Problem: I understand that using eval to convert a string to a function is considered bad practice e.g.

eval("my_func"());

From what I have found the correct way is to use window object e.g.

window["my_func"]();

This works absolutley fine except for when I need it inside a window listener e.g.

window.addEventListener("load", ()=>{
  function my_func(){
    alert("hi");
  }
  window["my_func"]();
});

It gives the error of "Uncaught TypeError: window.my_func is not a function"

I tried using the "this" keyword instead of window but no joy, I've tried not using an arrow function to no joy, I can still use eval but it is not best practice, not sure where to go here.

Any ideas?

cheers

Zen

Zenonline
  • 102
  • 9
  • `my_func` is not global here, you've to place that function definition to the global scope. Though much simpler would be just call `my_func();`. – Teemu Mar 03 '20 at 16:18
  • Assign an object to a constant inside the function you pass to `addEventListener`. Make the function a property of that object. Use that object instead of `window`. – Quentin Mar 03 '20 at 16:20

0 Answers0