user80855
user80855

Reputation: 1424

this keyword from a call back not working with typescript

class Util
{
    callback(callme: () => void)
    {
        callme();
    }
} 


class Greeter {
    greeting: string;
    util: Util;
    Me : Greeter;
    constructor(message: string) {
        this.greeting = message;
        this.util = new Util();
    }
    greet() {
        return "Hello, " + this.greeting;
    }

    callMe()
    {
        this.util.callback(this.greet);         
    }
}

var greeter = new Greeter("world");

var button = document.createElement('button');
button.textContent = "Say Hello";
button.onclick = function() {
    alert(greeter.callMe());
}

document.body.appendChild(button);

I am having problems with the this keyword, it is not pointing to the class when I do code like this. How do make this application work? this is pointing to window when used in callback like this...

link to code

Upvotes: 2

Views: 2903

Answers (1)

Edwin Dalorzo
Edwin Dalorzo

Reputation: 78579

Change it to

this.util.callback(this.greet.bind(this));

The problem is that when you pass a reference to your greet method, JavaScript just sees a function being passed as argument. When the function is executed it needs a new context and uses whatever "this" represents at that point.

To avoid this, you can bind your function to its context and avoid a new context is assigned to it when executed. To do this, you use bind. Its first argument lets you define the context object that should be used when the function is executed.

This would be somewhat equivalent to:

var self = this;
this.utils.callback(function(){
   self.greet();
});

Which is equivalent to the answer you got on comments using a TypeScript closure

() => this.greet();

Upvotes: 2

Related Questions