javascript - 类中的变量范围
问题描述
我有这个代码:
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
?对不起,如果我不清楚。
解决方案
使其成为实例属性,就像所有其他属性一样。在构造函数中:
this.cube = new THREE.Mesh(new THREE.BoxGeometry(w, h, d), new THREE.MeshPhongMaterial({color: color}));
然后参考:
scene.add(this.cube);
推荐阅读
- spring-boot - 识别历史清理的流程定义 ID (ttl)
- php - 我有来自 API 的 json 数据,并想使用 PHP 从响应中提取数据
- python - 通过 ScrapySpider 运行 SplashRequest 时出现 504 网关超时
- mysql - 删除所有重复的记录,但只有一条记录
- rest - 从其 URL 模式识别 REST 操作?
- pyomo - 需要帮助:约束和结果(Pyomo)
- java - 如何将 launch4j 与 Java 自定义运行时映像一起使用?
- android - 如何查找特定 SSID 的网络 ID?
- c# - 如何从给定数字开始实现此字符串生成行为?
- c# - 正则表达式仅提取具有特定单词的 a href