Posted on Saturday November 23, 2013

Using the this keyword with Typescript and a jQuery function

When you write Typescript, you’re forced by the compiler to use the “this” keyword when you want to access member variables or methods. If they’re static, you’re forced to use the name of the class (as you usually would in C#, although it’s syntactical).

This can cause problems when you bind jQuery button clicks to your own methods, and want to access member variables inside that method, as you are now inside the scope of the jQuery event and no longer your class. It’s one of the great ‘features’ of Javascript that the C# team overcame quite easily with lambdas, and in standard Javascript you usually overcome it by referencing the class instance in a variable named “that”, if you’re use Douglas Crockford’s pattern.

The solution in Typescript is to use their lambda expression syntax to maintain scope, and with it the Typescript compiler uses a _this variable if needed and does it all for you. For example:

This compiles down to: