未捕获的引用错误:初始化之前无法访问“类”

The*_*ner 14 javascript google-chrome

我有一个小的 vanila-js 项目。Chrome 的控制台给我标题错误。我的代码结构是这样的:

<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>
Run Code Online (Sandbox Code Playgroud)

控制台显示上线:var color=new Color();如何解决?我不知道为什么我有这个问题。PS:是的,我在堆栈上搜索了其他主题,但这些主题涉及框架或打字稿。没有人帮助我解决我的错误!这就是我创建该主题的原因。请不要留下缺点或大拇指,但请帮助我。

Cer*_*nce 13

类,就像用const和声明的变量一样let,在初始化它们的行运行之前不能被引用。例如,以下行为是禁止的:

console.log(foo);
const foo = 'foo';
Run Code Online (Sandbox Code Playgroud)

classes 也有同样的规则。在这里,您在线路运行init之前拨打电话。class Color修复方法是:

const foo = 'foo';
console.log(foo);
Run Code Online (Sandbox Code Playgroud)

或者,在这种情况下:

class Color {
  // ...
}
init(); // only call init once Color has been defined
Run Code Online (Sandbox Code Playgroud)

Color类移至顶部,或将init()调用移至脚本底部,或者以其他方式确保Color在您调用 时定义init

  • 这可以解释**类声明被提升,但不提升它们的值**的微妙之处。因此,代码可以在定义之前使用类名,只要该代码在定义之前不执行即可。详细信息请参见 [stackoverflow](/sf/answers/2487657441/) 和 [stackabuse](https://stackabuse.com/hoisting-in-javascript/#hoistingclasses)。 (3认同)