KodingRookie
KodingRookie

Reputation: 53

How to call a class from another ,js file?

I am pretty new to this and I am trying to understand classes in javascript. So I followed a tutorial online and everything seemed to work fine and when I tried to do the same like it was in the video I now get an error saying "Uncaught ReferenceError: MyClassName is not defined"

I have 2 files:

In class.js

class MyClass {
    constructor(city, state){
        this.city = city;
        this.state = state;

    }
    message(){
        console.log('Hey!');
    }
}

in app.js

const myClass = new MyClass();

const btn = document.getElementById('submit');


btn.addEventListener('click', myClass.message());

The error I get is "Uncaught ReferenceError: MyClass is not defined".

My question is how do I instantiate a class from another file? I know I am doing something wrong but I have no idea what it is.

Update: My HTML doc goes like this.

<body>

    <div class="form-group">
                <button id="submit"  name="submit">Submit</button>
    </div>
    


<script src="app.js"></script>
<script src="class.js"></script>

</body>
</html>

Please help, thank you for your time.

Upvotes: 5

Views: 5945

Answers (2)

YeetYeet
YeetYeet

Reputation: 100

Since you linked the app.js is linked before the class.js, it is loaded first, so you can't access MyClass. Switch the lines where you link app.js and class.js, and it should run with no errors.

<!DOCTYPE html>
<html lang="en">
  <body>
    <div class="form-group">
      <button id="submit" name="submit">
        Submit
      </button>
    </div>
  </body>
  <script type="text/javascript" src="class.js"></script>
  <script type="text/javascript" src="app.js"></script>
</html>

Upvotes: 1

MK.
MK.

Reputation: 832

I believe it's giving you that error because you imported the app.js file before class.js file. Try importing class.js first and then it should work. example:

<body>

    <div class="form-group">
                <button id="submit"  name="submit">Submit</button>
    </div>
    

<script src="class.js"></script>
<script src="app.js"></script>

</body>
</html>

Upvotes: 1

Related Questions