Hacker News new | ask | show | jobs
by DonHopkins 4433 days ago
Congratulations, you've set them up to get screwed every time they define a callback that uses "this" inside another function (which is an extremely common things to do in JavaScript). Any explanation of how "this" works that doesn't fully explain all the pitfalls of DYNAMIC BINDING of the KEYWORD "this" is just misleading and will teach people to write buggy code.

I'm not blaming you, it's not your fault, it's Brendan Eich's fault for such a crappy design. There is NO WAY to properly teach JavaScript without getting deep and dirty into the intricacies of how the virtual machine works and binds "this" dynamically at runtime.

You should explain why you should do "var self = this;" and use self instead of this inside of closures, because it's definitely going to bewilder new programmers when they see code in the real world that does that, and wonder why the fuck anyone would write something so crazy, and not realize that they should be writing crazy stuff like that themselves or else they will regret it.

It is very embarrassing to explain "this" after having extolled the virtues of lexical scoping and closures, having to explain that the variable you most often want to close over, "this", is not actually a variable, not lexically scoped the way it seems, but actually a magic keyword (as if that mattered to anyone learning the language).

The flaw is that "this" is dynamically bound in a way that 99% of programmers don't actually want it to be 99% of the time, and the bugs it causes are subtle and hard to spot, because you read the code as you meant it to behave, not as it actually does behave, so "this" looks just fine, but doesn't work the way it looks.

In the rare cases that you do actually want "this" to be dynamically bound instead of lexically scoped, there would have been many other ways to get that effect explicitly instead of implicitly.

The terrible way "this" works makes JavaScript code so much harder to understand and write and debug and prone to difficult to diagnose and spot bugs, so it's one of the first, most important things you should teach new programmers about the language, who should realize from day one that as cool and popular as it is, JavaScript is deeply flawed.