savram
savram

Reputation: 580

How do I assign a method to a variable in typescript?

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

let greeter = new Greeter("world");

let button = document.createElement('button');
let a  = greeter.greet;
button.textContent = "Say Hello";
button.onclick = function() {
    alert(greeter.greet());//works
    alert(a());//doesn't work
}
document.body.appendChild(button);

I'd like to store a class method in a variable, and then call it. How can I make this example work? It works if I store just "greeter" in "a", and then call greet, but I don't want to do it like that. I'm trying it on typescript playground

Upvotes: 3

Views: 1358

Answers (1)

Amit Beckenstein
Amit Beckenstein

Reputation: 1332

TL;DR:

let a  = greeter.greet.bind(greeter);

Actual explanation:

This actually doesn't have anything to do with TypeScript specifically, but with JavaScript and how this works.

When you assigned greeter.greet() to a, what you actually did was assign Greeter's class method greet() to a, instead of the greet() method of the Greeter class instance which you named greeter. Therefore, by bind()-ing greeter to the Greeter#greet() function, you assign greeter's greet() method to a.

For further reading:

  1. MDN article which explains this in JavaScript, specifically "The bind method" section

  2. TypeScript Wiki article about this in TypeScript

Upvotes: 5

Related Questions