Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
345 views
in Technique[技术] by (71.8m points)

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

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>
question from:https://stackoverflow.com/questions/65901271/jquery-3-5-1-js4055-uncaught-referenceerror-cannot-access-connectfour-before

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...