2
    interface IMySocks {
        start(): void;
    }

    declare var $;

    class MySocks implements IMySocks {

        private address: string;
        private protocols = [];
        private mySock: WebSocket;
start() {
        this.mySock = new WebSocket(this.address, this.protocols);
        this.mySock.onclose = this.onclose;
        this.mySock.onopen = this.onopen;
        this.mySock.onerror = this.onerror;
        this.mySock.onmessage = this.onmessage;
    }

private onopen(): void {
        this.sendIt();
        console.debug("OPEN");
    }

private sendIt() {
.....}

var my: IMySocks = new MySocks(); my.start();

So such class comes to Error in the subject. Intellisense and compilation found no error in typescript file. I am using VS2012 Ultimate update 2 with typescript 1.0. What wrong ?

Trhe problem raises when I call this.sendIt();

alerya
  • 3,125
  • 3
  • 28
  • 50
  • See http://stackoverflow.com/questions/16157839/typescript-this-inside-a-class-method or any other question tagged with `typescript` and `this` – Ryan Cavanaugh May 27 '14 at 07:41
  • 1
    doesn't work. Anyway the code using ()=> is rather ugly. Why TS doesn't make a error message on compilation stage ? Because TS guess this is right code ! – alerya May 27 '14 at 08:01

3 Answers3

2

Unlike some other programming languages like C# which would preserve the this context to be what you wanted automatically, the this context in JavaScript is a bit different. For more details, you might read this.

Instead of creating a closure to capture this, uou might also consider a more typical JavaScript approach using bind available in ES5 (Mozilla docs / MSDN docs):

this.mySock.onclose = this.onclose.bind(this);

bind returns a function that is bound to the provided this context (or any context you'd like). That function (onclose) will be called at run time with the proper context set.

WiredPrairie
  • 58,954
  • 17
  • 116
  • 143
1

The problem is that this in that case does not point to your instance of MySocks but to the instance of WebSocket.

If you want the this reference to work you could do the following

this.mySock.onopen = () => { this.onopen(); };
Dennis Korbar
  • 500
  • 2
  • 7
1

You need to use a lambda if you plan to pass a function around. Either what Dennis recommends or :

private onopen =  () => {
        this.sendIt();
        console.debug("OPEN");
    }

For the reason see : https://www.youtube.com/watch?v=tvocUcbCupA&hd=1 It is because the calling context is lost if you simply pass a member function without using a lambda (and let someone else call it).

basarat
  • 261,912
  • 58
  • 460
  • 511