Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

268
Visualizações
Module vs normal javascript for function within html

I have two javascript functions defined in a normal <script> tag and one imported within a <script type="module"> tag:

<script type="module">
    import { mean } from "./node00.js";
    console.log(mean(1,2,3)); // OK -- just to confirm this works fine
</script>

<script>
    function xNew(x) { console.log("Calling xNew"); }
</script>

<span onclick="mean(1,2,3,4)">Hello</span>
<span onclick="xNew(5)">It's me.</span>

It seems that the mean function within the module is not accessible to the html, whereas the xNew function within the normal script tags is. What is the scoping and accessibility of these two items? And if module makes the javascript hidden from the html what would be the point of using it?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

From the nature of module, modules can talk to modules by import and export only (No communications outside of modules), but you can add events on DOM objects via document or window which is shared for all modules.

<script type="module">
function sum(a,b) {
    console.log('Calling sum');
    return a+b;
}
document.getElementById("test-sum").onclick = () => sum(2,3)
</script>

<script>
function xNew(x) {
    console.log("Calling xNew");}
</script>

<span id="test-sum">Hello</span>
<span onclick="xNew(2)">It's 'a me, mario</span>

about 4 years ago · Juan Pablo Isaza Relatório

0

It seems a script tag having type="module" attribute specifies that it to be considered as a Javascript module. It may be importing other Javascript module(s) inside it and becomes a "top-level" module for the imported modules.

For example:

// file "module.js"
export var someVar = "Some data";

export function someFunc() {
    return " for output";
}

// this has no "export" prefixed hence cannot be used outside this module 
function someOtherFunction() {
    return 1;
}

<script type="module">
    import {someVar, someFunc} from './module.js';

    // "Some data for output"
    console.log(someVar + someFunc());
</script>

In the example above the module that is created is imported using the import statement.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda