1

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?

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

2 Comments

Hi there, thank you for the reply. It works like a charm :) Can you explain me what the fat-arrow is? It looks like lambda expressions as I know them from C#.
Their main purpose is to preserve scope - you can use them as shorthand for creating functions on the fly.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.