jquery-3.5.1.js:4055 Uncaught ReferenceError: Cannot access 'connectFour' before initialization

Viewed 571

I'm trying to console.log('hi') which is passed using a function inside the $(document).ready()` in jQuery. The problem is that the console in Chrome shows me the following error:

jquery-3.5.1.js:4055 Uncaught Reference Error: Cannot access connect Four before initialization
at HTML Document. (grid.html:26)
at might Throw (jquery-3.5.1.js:3762)
at process (jquery-3.5.1.js:3830)

<script>
  class connectFour {
    constructor(selector) {
      console.log(selector);
    }
  }
</script>

<div id="htmlConnectFour"></div>
<script src="https://code.jquery.com/jquery-3.5.1.js" integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous"></script>
<script>
  $(document).ready(function() {
    const connectFour = new connectFour('hi');
  });
</script>

1 Answers

The issue is because you're giving the variable the same name as the class.

Note that by standard JS naming convention, classes should have upper pascal case names. Variables should have lower pascal case. Following these rules avoids the issue:

class ConnectFour {
  constructor(selector) {
    console.log(selector);
  }
}

$(document).ready(function() {
  const connectFour = new ConnectFour('hi');
});
<div id="htmlConnectFour"></div>

<script src="https://code.jquery.com/jquery-3.5.1.js" integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous"></script>

Related