【问题标题】:How do I create global variables I can use across my modules?如何创建可以跨模块使用的全局变量?
【发布时间】:2021-03-01 10:48:28
【问题描述】:

我将场景从文件 sceneSetup.js 导入到 initFloor1.js 并得到错误 ReferenceError: scene is not defined 找不到这个问题的解决方案,不明白是javascript的问题还是Threejs的问题

sceneSetup.js:

export let camera, controls, renderer, labelRenderer, renderer3D, arrow, label, scene;

initFloor1.js:

import * as THREE from 'three';
import { camera, controls, renderer, labelRenderer, renderer3D, arrow, label, scene } from './../sceneSetup.js'
            
export function initFloor1() {
                
    scene = new THREE.Scene();

我的项目文件夹:

|- src
|  |- 3d-scene
|     |- sceneSetup.js
|     |- Floor1  
|        |- initFloor1.js

【问题讨论】:

  • 不是threeJS的问题。
  • 什么是THREE
  • JavaScript 库。如您所见,它是在“initFloor1.js”中导入的
  • sceneSetup.js 的导出都是未定义的。你认为为什么会被定义?
  • 我不知道为什么它们都是未定义的。你能解释一下吗?

标签: javascript


【解决方案1】:

ChrisG 建议的解决方案:导出对象并编辑其值

const globals = {
      camera: null,
      controls: null,
      renderer: null,
      labelRenderer: null,
      renderer3D: null,
      arrow: null,
      label: null,
      scene: null
    };
    
    export { globals };

【讨论】:

    【解决方案2】:

    使用window.variableName在中心位置声明,然后您可以跨站点访问。

    window.camera=null;
    window.controls=null;
    

    等等

    【讨论】:

    • 我认为 OP 试图避免这种情况
    • 这是 OP 可以使用的一种方式。我分享是因为这是有效的方式,我在整个网站上都使用它..
    • 这并没有提供问题的答案。要批评或要求作者澄清,请在他们的帖子下方留下评论。 - From Review
    • @Eydrian :为更好理解而修改
    猜你喜欢
    • 2016-10-20
    • 1970-01-01
    • 2017-06-02
    • 1970-01-01
    • 2017-04-30
    • 2014-02-18
    • 1970-01-01
    • 2019-07-06
    相关资源
    最近更新 更多