user3122410
user3122410

Reputation: 13

Passing functions through classes

I'm brand new to typescript and I have a question. I wrote the following code:

class FunctionMachine {
 name: string;
 constructor(_name: string) {
  this.name = _name;
 } 
 sayName() {
  console.log(this.name);
 }
 sayNameWithCallback(callback){
  console.log(this.name);
  callback();
 }
}

var fmHans = new FunctionMachine("Hans");
var fmOle = new FunctionMachine("Ole");
fmOle.sayName();
fmHans.sayNameWithCallback(fmOle.sayName);

I would expect it to Write "Ole, Hans, Ole" when run. Instead, it returns "Ole, Hans, ".

It looks like "this." refers to something other than what I expect when I use fmOle.sayName as argument.

Is this not supported in TypeScript, or do I need to rewrite my code?

Upvotes: 1

Views: 41

Answers (1)

Fenton
Fenton

Reputation: 250872

You need to protect your scope in this case. There is a trick Ryan Cavanaugh has mentioned before whereby you use a fat-arrow to do this on the class:

class FunctionMachine {
   name: string;
    constructor(_name: string) {
        this.name = _name;
    } 

    sayName = () => { // <-- This is the clever bit
        console.log(this.name);
    }

    sayNameWithCallback(callback) {
        this.sayName();
        callback();
    }
}

var fmHans = new FunctionMachine("Hans");
var fmOle = new FunctionMachine("Ole");

console.log('First Call');
fmOle.sayName();

console.log('Second Call');
fmHans.sayNameWithCallback(fmOle.sayName);

Upvotes: 1

Related Questions