+ 8
Functions and variables in different scripts
In the following code, when I try to call a function that is inside the script tag (module type) it gives an error, even if I wait for the page to load completely. Also I can't use the variables outside of that script either. https://sololearn.com/compiler-playground/WT9c5QA54R73/?ref=app
7 Respostas
+ 9
Usually you would not use the type='module' like this. You would place the javascript code in an external file where you would only export the exposed part, and in the script tag you can import it or just specify the js file path in src attribute.
Importing from a module creates a separate scope, so your f2 function is not available for the button click.
You can attach the function to the global scope by copying it under the window object
<script type="module">
function f2() {
console.log("function 2");
}
window.f2 = f2;
Doing this, your f2 button will work.
But this is not recommended, read here why.
https://stackoverflow.com/questions/44590393/es6-modules-undefined-onclick-function-after-import?noredirect=1&lq=1
the code will also work if you remove the type="module" attribute.
+ 7
Tibor Santa, f4 and f5 won't work even after removing module type because both constant and f4 are in a separate scope. This avoids accessing them and results in error when clicking f4 and f5 button.
+ 5
Variables declared via var have a functional scope. They are only available within the current function or global object.
So in order for a variable to become global, it needs to be declared using window:
<script type="module">
window.f2 = f2;
window.variable = "function 3";
...
Variables of type let and const have a block scope.
Therefore, constant is only visible in an unnamed function waiting for the html document to be fully loaded:
window.onload = () => {
const constant = "function 5";
window.constant = constant;
window.f4 = f4;
...
+ 3
Tibor Santa Thanks so much for the explanation
I think I'll be using the window object more often..
+ 3
Solo ,
Thank you very much too, so can I declare global variables in any script and use them in another?
+ 3
NinjaGamer yes, of course you can declare any object global via
window in the browser and global in the Node.js.
In large projects, all global variables are specially collected in one file so as not to get confused in the names.
I have completed my previous answer...đ
+ 3
NinjaGamer here is another example about global variables that can be used, including in JavaScript...đ:
https://sololearn.com/compiler-playground/WnnXLKBtBfjZ/?ref=app