【问题标题】:Variable Scope in Classes类中的变量范围
【发布时间】:2021-02-08 03:15:02
【问题描述】:

我有这个代码:

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() 方法放在一边,因为这不是我关注的重点。

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

【问题讨论】:

  • this.cube = new Three.Mesh(...);

标签: javascript class variables scope


【解决方案1】:

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

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

然后参考:

scene.add(this.cube);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-03-21
    • 2022-01-11
    • 2011-05-21
    • 2013-07-28
    相关资源
    最近更新 更多