0

When I try to pass this.someFunction to someClass.addEventListener() (other class than this) I get following error

TypeError: undefined has no properties when the event is executed. So it seems like reference to this.someFunction is valid only locally, but does not work from context of other class?

code is like this (deleted irelevant parts):

class ThreeJS {

  constructor(container) {
    this.renderer = this.initRenderer(container);
    this.camera = new THREE.PerspectiveCamera(45, this.renderer.aspectRatio, 1, 2000);
    this.controls = this.initControls(this.camera);
  }

  initRenderer(container) {
    let renderer = new THREE.WebGLRenderer({
      antialias: true
    });
    return renderer;
  }

  initControls(camera) {
    let controls = new THREE.TrackballControls(camera);
    console.log(this.renderer); // Here this.renderer is defined
    controls.addEventListener('change', this.render);
    return controls;
  }

  render() {
    console.log(this.renderer); // Here this.renderer is undefined
    this.renderer.render(this.scene, this.camera);
  }

}

function animate() {
  requestAnimationFrame(animate);
  threeJS.controls.update();
}

// main()
var threeJS = new ThreeJS(document.getElementById("GLScreen"));
animate();
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/93/three.js"></script>
<script src="https://threejs.org/examples/js/controls/TrackballControls.js"></script>
TheJim01
  • 8,411
  • 1
  • 30
  • 54
Prokop Hapala
  • 2,424
  • 2
  • 30
  • 59
  • I transferred your code into a snippet. As written, it does not throw any errors. That said, I also didn't see it firing TrackballControls `change` events. – TheJim01 May 31 '18 at 20:50
  • If a class method is used by some other class, isn't better to create a global function, or else create a class with the shared method and extend it? – Canta May 31 '18 at 20:55
  • Also, i think you can call a class method of its instance, not the generic class. – Canta May 31 '18 at 20:56
  • Do `console.log(this)` instead of `console.log(this.renderer)` to find out why. – Bergi May 31 '18 at 20:58

0 Answers0