2

I have a basic question about class definition in JavaScript. Let me explain my problem, here is my class (this is a simplified version for the sake of clarity):

var RemoteCursor = function(canvas_id) {
    this.ws_sendjoingroup = function() {
      console.log('Dummy log just for debug');
    }
    this.ws_cursor_onopen = function() {
      console.log('ws_cursor_on open: (debug)');
      this.ws_sendjoingroup();
    }
    this.ws_start_remote_cursor = function() {
        this.ws_remote_cursor = new WebSocket('ws://localhost/ws');
        this.ws_remote_cursor.onopen = this.ws_cursor_onopen;
    }
}

I call this class inside my HTML page like this:

<script>
    window.onload = function() {
        var cursor1 = new RemoteCursor("usimage_cursor");
        cursor1.ws_start_remote_cursor();
    }
</script>

But when the onopen callback fires, inside the function ws_cursor_onopen the context is different, this have nothing defined and I got the error:

Uncaught TypeError: this.ws_sendjoingroup is not a function!

The typeof(this.ws_sendjoingroup) is undefined

How can I pass the function inside my instance of RemoteCursor as the callback for the onopen?

1 Answer 1

1

Try using bind(), it helps lock the value of this. Otherwise you can structure it a bit differently;

var RemoteCursor = function(canvas_id) {
  this.ws_sendjoingroup = ws_sendjoingroup;
  this.ws_cursor_onopen = ws_cursor_onopen;
  this.ws_start_remote_cursor = ws_start_remote_cursor.bind(this);


  function ws_sendjoingroup() {
    console.log('Dummy log just for debug');
  }

  function ws_cursor_onopen() {
    console.log('ws_cursor_on open: (debug)');
    ws_sendjoingroup();
  }

  function ws_start_remote_cursor() {
    this.ws_remote_cursor = new WebSocket('ws://localhost/ws');
    this.ws_remote_cursor.onopen = this.ws_cursor_onopen;
  }
}

Also, be very aware that using inheritance and OOP programming in JavaScript usually ends poorly and is a somewhat frowned upon practice by more experienced developers. You can learn more about this with D. Crockford's wonderful talk, The Better Parts here.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks @sgarcia.dev. It's working with your suggestion. I also defined the: this.ws_cursor_onopen = ws_cursor_onopen.bind(this)
Great @Bulha. Please mark it as correct answer if it's correct so other people can stop checking this question thinking you still need an answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.