0

How can ordinary, top level functions, that are part of the default closure be exposed to the JS console in the browser (for debugging reasons)?

// default.js
function iWantToCallThisFunction() {
  console.log("test successfull");
}

There's this answer from 2014, which doesn't seem to be valid anymore: https://stackoverflow.com/a/9054881/6204346

At least a current Chrome can't find the function and defaults to undefined.

Flagging the function with export doesn't seem to make a difference. It would probably be possible but inconvenient to safe the function in the window. Is there a better way?

MPW
  • 161
  • 1
  • 3
  • 16
  • 1
    try `window.iWantToCallThisFunction = function() { console.log("test successfull"); }` and call `window.iWantToCallThisFunction()` OR `var iWantToCallThisFunction= function() { console.log("test successfull"); }` and `iWantToCallThisFunction()` – demo Mar 16 '21 at 12:03
  • Judging from your text, especially the "export" part, you are obviously inside an esm, which isn't global scope. You can do extremely dirty tricks, but should much rather just add it to `window`, as you already noticed. – ASDFGerte Mar 16 '21 at 12:10
  • No, it's really just top level es6 code. No modules no other stuff. Export was just a test. I would like to learn about those ”extremely dirty tricks“ as it's just for debug reasons. – MPW Mar 18 '21 at 08:38

1 Answers1

0

That's very strange that it's showing as undefined. If you want to view the contents of the function (and it's already loaded and declared) just type iWantToCallThisFunction without the parenthesis at the end. If you want to call the function, just type iWantToCallThisFunction() with parenthesis. You could also try setting the function as a variable. I think that this is because the function isn't actually being created by the time you go into the JavaScript console. Make sure the right JavaScript file is connected, and that there's no errors. If the file has other stuff in it, that might be interfering with this function being made, so maybe try it in a blank file by itself.

Tyler Selden
  • 281
  • 2
  • 14
  • The function is there and can be executed by JS internally. It's just the the scope of the console doesn't know about it. – MPW Mar 18 '21 at 08:36