Why can my script redefine functions from another file?

0
6
Asked By CuriousCoder42 On

I'm trying to understand how my injected script can modify functions that are declared in another JavaScript file. I have an HTML file with some inline JavaScript and a link to an external script. However, it seems like the code in the linked file can redefine my inline functions. For example, in my HTML, I have a `send` function and an `onclick` event that triggers it. But in the external file, I'm redefining the `send` function, and when I press the button, I get an alert saying 'Wrong send function!' instead of my original alert. What allows the external file to access and modify my inline function?

2 Answers

Answered By ScriptSavant99 On

It sounds like your `other.js` file is in the same global scope as your inline code. When you load scripts in a regular way without using modules, all variables declared are treated as global. To prevent this, you can use `` for your scripts, which creates a new scope for those variables. This separation helps avoid accidents like redefining functions.

Answered By TechieTim123 On

Exactly! Top-level variable assignments are global unless you use a module. If you use `const` or declare functions inside a module, you can prevent collisions like this. It’s a good practice to ensure you're not affecting global variables, especially in larger projects.

CuriousCoder42 -

Thanks for the tip! I'll definitely look into using modules.

CodeWhiz88 -

Yeah, modules are super helpful for managing scope better!

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.