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
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.
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.
Yeah, modules are super helpful for managing scope better!
Thanks for the tip! I'll definitely look into using modules.