0

I have my file structure like this:

classfile.js

class Car {
    constructor(name, year) {
      this.name = name;
      this.year = year;
    }
  }

mainfile.js

import {Car} from './classfile.js';  // Added this
const myCar = new Car("Ford", 2014);

function myFunction() {
    document.getElementById('demo').innerHTML = myCar.name + " " + myCar.year;   
}

main.html

<!DOCTYPE html>
<html>
    <head>
        <script src="classfile.js"></script>
        <script type="module" src="mainfile.js"></script>
    </head>
<body>
<h2>JavaScript Class</h2>
<p>How to use a JavaScript Class.</p>
<p id="demo" onclick="myFunction()">Click Me</p>
</body>
</html>

I keep getting errors myFunction() is not defined.

How do I make functions in module type to execute?

Aakash
  • 63
  • 1
  • 6
  • Aside from the core problem (see the duplicate) `import {Car} from './classfile.js'; // Added this` requires that you `export` the `Car` class from the module. You should also remove `` since you are `import`ing it where you need it. – Quentin Apr 21 '22 at 15:12
  • There are a couple of errors there. The main one you've asked about is addressed by [this question's answers](https://stackoverflow.com/questions/62645623/why-theres-error-in-onclick-when-i-have-module-in-script-tag): `onxyz`-attribute-style event handlers can only call global functions (one of the many reasons not to use them), and top-level declarations in modules *aren't* global functions like they are in non-module scripts (one of the many good things about modules). Instead, use [modern event handling](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener). – T.J. Crowder Apr 21 '22 at 15:13
  • A couple of other issues: 1. `classfile.js` doesn't export `Car` (at least not in the code you've shown). 2. The `src` attribute of a `type="module"` `script` element must have a path of some kind on it unless you're using import maps (which I'm guessing you aren't). So yours should be `src="./mainfile.js"`. – T.J. Crowder Apr 21 '22 at 15:15

0 Answers0