Veit's Blog

Hej! đź‘‹ Welcome to my curated space of insights on software development and the tapestry of life.

Pitfall with "this" in TypeScript

2015-08-30

Recently I stumbled accross a strange behaviour with the “this” reference in TypeScript.

class TestClass {
    value:string;

    constructor(value:string) {
        this.value = value;
    }


    doSomething():string {
        return "Value: " + this.value;
    }
}


var objectRef = new TestClass("Simple Param");
var methodRef = objectRef.doSomething;

document.write(objectRef.doSomething())
document.write(" --- ")
document.write(methodRef());

Somehow I expect the output Value: Simple Param --- Value: Simple Param. Instead Value: Simple Param --- Value: undefined is displayed. My humble opinion is that method references always should be bound to an object. But the reasons is clear: TypeScript is a superset of JavaScript and so the semantics on “this” remains unchanged.