无法在JavaScript类中调用函数
问题描述:
我在写一个THREE.js图形程序,并且想用Javascript创建一个BodyPart类,但是我不能调用这些方法。下面的代码打印“调用测试”,但不是“调用测试”。我试过把功能测试外部BodyPart并将其与原型相关联,但也会发生同样的问题。这段代码有什么问题?无法在JavaScript类中调用函数
function BodyPart (name){
this.name = name;
this.test = function(){
alert('called test');
}
this.geometry = new THREE.BoxGeometry(1, 1, 1);
this.material = new THREE.MeshNormalMaterial({ color: 0x00ff00 });
return new THREE.Mesh(this.geometry, this.material);
}
var backFoot = new BodyPart("Back foot");
alert('calling test');
backFoot.test();
答
你的问题是,你从你的函数返回THREE.mesh:
return new THREE.Mesh(this.geometry, this.material);
这样做是为了网格而不是一个属性:
this.mesh= new THREE.Mesh(this.geometry, this.material);
答
这是因为你返回THREE.Mesh
从函数中,并将其保存到backFoot
。因此,你的有效尝试做:
new THREE.Mesh(this.geometry, this.material).test();
当你调用test
这样的:
backFoot.text();
这是无效的,因为THREE.Mesh
不具备的功能test
。不要从函数返回,设置,作为一个属性:
function BodyPart(name) {
this.name = name;
this.test = function() {
alert('called test');
}
this.geometry = new THREE.BoxGeometry(1, 1, 1);
this.material = new THREE.MeshNormalMaterial({
color: 0x00ff00
});
this.mesh = new THREE.Mesh(this.geometry, this.material); //Now, as a property instead of returning.
}
var backFoot = new BodyPart("Back foot");
alert("calling test");
backFoot.test();
//Access the mesh with backFoot.mesh
<script src="//cdnjs.cloudflare.com/ajax/libs/three.js/r70/three.min.js"></script>
嗯,我认为这可能最终穿透我的厚头骨。只要我能够调用backFoot.test(),您的解决方案就可以工作,但表示后脚的多维数据集不会出现在图像中。看起来,制作一个对象的成本是网格现在是对象的属性,而不是对象本身。是对的吗?因此,我现在不需要调用scene.add(backfoot),而是需要调用scene.add(backfoot.mesh) - 事实上,当我开始创建整个身体部位时,scene.add( .mesh)。 – struggling
@struggling是的,这是一个属性。返回会导致各种麻烦,我不建议这样做。构造一个对象通常会给出一个构造函数类型的新对象,但是会覆盖它 – Li357