11

I have little vanila-js project. Chrome's console gives me error from title. Structure of my code is like this:

<script type="module">

    import * as THREE from 'https://unpkg.com/three/build/three.module.js';

    import { TrackballControls } from 'https://unpkg.com/three/examples/jsm/controls/TrackballControls.js';

    var camera, scene, renderer, controls;

    init();
    animate();

function init() {
//code here
var list_of_objects=generate_first();}

 class Color{


        constructor() {
            this.R=getRandomInt(0,255);
            this.G=getRandomInt(0,255);
            this.B=getRandomInt(0,255);
            this.hex=this.fullColorHex(this.R,this.G,this.B);
        }
//rest of code}

 function generate_first() {
        var list_of_gens=[];
        var color=new Color();}

</script>

Console indicates on line : var color=new Color();How to fix it? I have no idea why i have this problem. PS:Yes, I've searched other topics on stack, but those topics touched frameworks or typescript. None helped me with my bug! That's why I created that topic. Please, don't leave minuses or thumbs down but help me.

The Trainer
  • 633
  • 1
  • 3
  • 19

1 Answers1

10

Classes, like variables declared with const and let, cannot be referenced before the line that initializes them runs. For example, the following is forbidden:

console.log(foo);
const foo = 'foo';

classes have the same rule. Here, you're calling init before the class Color line has run. The fix is to do:

const foo = 'foo';
console.log(foo);

or, in this case:

class Color {
  // ...
}
init(); // only call init once Color has been defined

Move the Color class up to the top, or move the init() call to the bottom of the script, or otherwise somehow make sure Color is defined by the time you call init.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • 2
    This could explain the subtlety that **class declarations are hoisted, but not their value**. So code can use a class name before it's defined, as long as that code doesn't execute before it's defined. Details at [stackoverflow](https://stackoverflow.com/a/35537963/673991) and [stackabuse](https://stackabuse.com/hoisting-in-javascript/#hoistingclasses). – Bob Stein Jan 10 '22 at 16:31