Thursday, 25 May 2017

"this" in JavaScript/TypeScript

I have been struggling with using "this" in JavaScript, ever since I got into that area of programming.

There are lots of warnings on the web, where programmers who are used to a certain behaviour regarding "this" (Like me) can fall into this trap.

I recently found some really good resources that explain it.

There's one1 that explains it a little regarding "this" in JavaScript.

But as I have been writing in TypeScript, I was looking for an explanation that focuses on TypeScript and helps me find the best solution to deal with this. I found that one in [2].

For example

So I've got some code that could use a bit of a look-over.

Here's the troublesome bit.

TypeScript has an excellent Tutorial, which I've used time and again to write my things. One of the pages I've used is the explanation regarding HTTP which you can find at [3].

In it they mention a "handleError" method, which can handle HTTP errors of the PlayerService. Convenient, so I used it. It works.

Next, I wished for the handleError method in the PlayerService that takes care of HTTP connections to notify the ErrorsService. So naturally, I inject the ErrorsService into the PlayerService.

Unfortunately, in the handleError, the ErrorsService is 'undefined'. (See line 30 in the gist below)

It is explained in reference [2] why this is, but I like the following quote:
“The biggest red flag you can keep in mind is the use of a class method without immediately invoking it. Any time you see a class method being referenced without being invoked as part of that same expression, this might be incorrect.”
Now there are several solutions for this described in [2].

The solution below is what I came up with on my own, and I don't really like it, but it works.

Local Fat Arrow

I prefer the solution called the "Local Fat Arrow", which looks like this:
I love it!


[1] Mozilla Developer Network - javascript:this
[2] Github/Microsoft/TypeScript - 'this'in TypeScript'this'-in-TypeScript

No comments:

Post a Comment