Hacker News new | ask | show | jobs
by MarkyPc3 4434 days ago
If the beginner understands functions I tell them it's the specific object running the function call. If not, I tell them it's the object that owns the most immediate scope (as in the one "running the code"). Also important here is the definition of what an object is. The key sentence to memorize is: "An object is an instance of a class" which is to say that the two are not the same. Saying a class is a blueprint and an object is the actual house that was built according to the blueprint (the class definition)is a good way to get this through. "This" in the above analogy more easily means a reference to a specific house.
1 comments

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.