Ludwig
Ludwig

Reputation: 209

Trying to instantiate JavaScript class in a html file

I'm trying to instantiate a JavaScript class in another HTML file.

Here is the JavaScript class:

class Puzzle {
  constructor(fenStart, pgnEnd) {
    this.fenStart = fenStart;
    this.pgnEnd = pgnEnd;
  }
}

module.exports = Puzzle;

And here is the HTML file:

<!DOCTYPE html>
<html>
    <body>
        <script src="jquery-3.2.1.min.js"></script>
        <script src="class.js"></script>
        <p id="demo"></p>

        <script>
            var demoEL = $('#demo');

            const x = new Puzzle("fenStart", "pgnEnd");

            demoEL.html(x.fenStart);
        </script> 
    </body>
</html>

However when ever I open the HTML file in chrome nothing appears on the page. And in the developer console I get the error "Uncaught ReferenceError: module is not defined, at class.js:8" How can I properly instantiate the puzzle class in this HTML file?

PS: I read that JQuery might be needed for this so I downloaded "jquery-3.2.1.min.js" and included it in the same folder as the JavaScript class and the HTML file.

Upvotes: 1

Views: 2218

Answers (2)

OnlySalman
OnlySalman

Reputation: 108

there is no need to say module.exports = Puzzle; this is what I did and it works fine.

JS

class Puzzle {
 constructor(fenStart, pgnEnd) {
this.fenStart = fenStart;
this.pgnEnd = pgnEnd;
 }}

HTML

<!DOCTYPE html>
 <html>
  <body>
     <script src="jquery.min.js"></script>
     <script src="class.js"></script>
     <p id="demo"></p>

     <script>
        var demoEL = $('#demo');

        const x = new Puzzle("fenStart", "pgnEnd");

        console.log(x.fenStart);
        console.log(x.pgnEnd);
    </script> 
    </body>
   </html>

since we are on the subject I highly recommend of using pseudoclassical pattern this pattern will make your life much easier if you are planning to add a function to your class

just to clarify this is an example of your class :

pseudoclassical patern - HTML :

<!DOCTYPE html>
  <html>
  <body>
    <script src="jquery.min.js"></script>
    <script src="class.js"></script>
    <p id="demo"></p>

    <script>
        var demoEL = $('#demo');

        const x = new Puzzle("fenStart", "pgnEnd");

        console.log(x.fenStart);
        console.log(x.pgnEnd);
        var bla = x.bla();
        console.log(bla);
    </script> 
</body>

pseudoclassical pattern - JS :

var Puzzle = function(fenStart,pgnEnd){
this.fenStart = fenStart;
this.pgnEnd = pgnEnd;
}


Puzzle.prototype.bla = function(){ // some other function
return "bla";
}

that's all, have a nice coding.

Upvotes: 0

Pritam Bohra
Pritam Bohra

Reputation: 4319

In that case, you don't need module.exports You can directly create the object and update the DOM. If at all you want to use modules in the browser you can use a module bundler like webpack

Upvotes: 1

Related Questions