Since Typescript supports “true” object-oriented programming using the ‘class’ and ‘interface’ keywords, there seems to be an expectation that the semantics of JavaScript is suspended and replaced by Something Completely New. This is not the case!
Remember, Typescript is a syntactic extension of JavaScript and compiles to JavaScript. The underlying concepts remain unchanged. (Un)fortunately (depending on your point of view and your expectations), this is also true for the ‘this’ keyword.
Let’s have a look at some StackOverflow questions regarding the meaning of ‘this’:
- The this keyword in typescript. Is it a bug?
- “this” in a method call in TypeScript?
- Is there an alias for ‘this’ in TypeScript?
- Using arrow functions in TypeScript: how to make them class methods?
The questions assume that a callback function passed to another function will be executed in the context of the original object, therefore retaining the semantics of ‘this’ identified the original object:
myFoo(){
otherFoo.otherBar(this.myBar);
}
In JavaScript, however, the function myBar is executed with ‘this’ referring, depending on the implementation of otherBar, to the otherBar function, or something completely different.
Do not despair, though, there are a couple of possible solutions:
- arrow functions (using the => operator)
- saving ‘this’ to a local variable (which the => operator compiles to in JS)
- using .bind()
- using jQuery’s $.proxy()