Pitfall with "this" in TypeScript
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.