0

I'm writing a THREE.js graphics program and I want to set up a BodyPart class in Javascript with some methods - but I can't call those methods. The code below prints 'calling test', but not 'called test'. I've tried putting the function test outside BodyPart and associating it with the prototype, but the same problem occurs. What's wrong with this code?

        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();
struggling
  • 21
  • 6

2 Answers2

1

Your problem is that you return THREE.mesh from your function:

return new THREE.Mesh(this.geometry, this.material);

Do this to make mesh a property instead:

this.mesh= new THREE.Mesh(this.geometry, this.material);
Robert Moskal
  • 21,737
  • 8
  • 62
  • 86
0

This is because you return a THREE.Mesh from the function, and save it into backFoot. Thus, you're effective trying to do:

new THREE.Mesh(this.geometry, this.material).test();

When you call test like this:

backFoot.text();

This is invalid because THREE.Mesh doesn't have the function test. Don't return from the function, set that as a property:

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>
Andrew Li
  • 55,805
  • 14
  • 125
  • 143
  • Ah, I think it may finally be penetrating my thick skull. Your solution worked insofar as I was able to call backFoot.test(), but the cube representing the back foot stopped appearing in the image. It seems that the cost of making backfoot an object is that the mesh is now a property of the object, rather than the object itself. Is that right? Therefore, instead of calling scene.add(backfoot), I now need to call scene.add(backfoot.mesh) - and indeed, when I get round to creating a whole slew of body parts, scene.add(.mesh). – struggling Oct 02 '16 at 10:36
  • @struggling Yes, it's a property. Returning can cause all kinds of trouble and I don't recommend doing it. Constructing an object usually gives a new Object of the constructor type, but returning overrides that – Andrew Li Oct 02 '16 at 13:11