I know this is probably painfully basic, but i am having a tough time wrapping my head around it.
class Main
{
constructor()
{
requestAnimationFrame(this.update); //fine
}
update(): void
{
requestAnimationFrame(this.update); //error, because this is window
}
}
It appears to be the case that I need a proxy, so lets say using Jquery
class Main
{
constructor()
{
this.updateProxy = $.proxy(this.update, this);
requestAnimationFrame(this.updateProxy); //fine
}
updateProxy: () => void
update(): void
{
requestAnimationFrame(this.updateProxy); //fine
}
}
But coming from an Actionscript 3 background, I am not really sure what is happening here. Sorry I am not sure where Javascript begins and TypeScript ends.
updateProxy: () => void
And also, I am not convinced I am doing this right. The last thing I want is most of my class having a a() function which needs to be accessed with aProxy()
as I feel I am writing the same thing twice? Is it normal?
In short, the this keyword always has a reference to the object that called the function.
In Javascript, since functions are just variables, you can pass them around.
Example:
When you do the following with jQuery:
What you are doing is overriding that context. Behind the scenes jQuery will guive you this:
If you write your methods like this, 'this' will be treated the way you expect.
Another option would be to bind 'this' to the function call:
The problem arises when you pass a function as a callback. By the time the callback has executed the value of "this" could have changed to the Window, the control invoking the callback, or something else.
Make sure you always use a lambda expression at the point you pass a reference to the function to be called back. For example
This compiles to something like
Because the addFile function is being called on a specific object reference (_this) it does not use the "this" of the invoker but instead the value of _this.
See page 72 of the typescript language specification https://github.com/Microsoft/TypeScript/blob/master/doc/TypeScript%20Language%20Specification.pdf?raw=true
Arrow Function Expressions
In the example
This is the actual generated Javascript:
If you want
this
captured the TypeScript way of doing this is via arrow functions. To quote Anders:Here is the way I like to use this to my advantage:
View this in the TypeScript Playground
You can see that in the generated JavaScript
this
is captured outside the function call:so the
this
value inside the function call (which could bewindow
) would not be used.To learn more: “Understanding
this
in TypeScript” (4:05) – YouTube