首页 > 解决方案 > 类中的变量范围

问题描述

我有这个代码:

class Cube {
  constructor(x, y, z, w, h, d, color) {
    this.x = x;
    this.y = y;
    this.z = z;
    this.w = w;
    this.h = h;
    this.d = d;
    this.color = color;
    let cube = new THREE.Mesh(new THREE.BoxGeometry(w, h, d), new THREE.MeshPhongMaterial({color: color}));
  }
  add() {
    scene.add(cube);
  }
  static render() {
    renderer.render(scene, camera);
  }
}

我正在尝试制作 Three.js 的东西,但这不是重点,所以将 render() 方法放在一边,因为这不是我关注的重点。

我在 中有cube变量constructor(),但我希望能够访问 中的cube变量add(),但是由于范围,它会引发错误。有没有办法让它能够在整个类中使用,而不必将变量声明放在类之外Cube?对不起,如果我不清楚。

标签: javascriptclassvariablesscope

解决方案


使其成为实例属性,就像所有其他属性一样。在构造函数中:

this.cube = new THREE.Mesh(new THREE.BoxGeometry(w, h, d), new THREE.MeshPhongMaterial({color: color}));

然后参考:

scene.add(this.cube);

推荐阅读