Saturday, September 20, 2014

MakerSquare Day 18: I am beginning to love this. (4/5)

To be sure, when I say "this," I am referring to something very particular: Javascript's "this", which is a reserved keyword that refers (roughly speaking) to the context in which it's called.

So, for example, if I write a function--let's call it contextA--and I give that function a property with a return value of "Ben," then any time I'm in contextA and I call, I'm going to get back "Ben."

But if, let's say, contextA calls another function--and, off the top of my head, let's call this one contextB--and contextB calls, it will no longer give back "Ben."

Now, I'm sure, given 10 minutes, I could come up with some non-computer-y analogy that might make this clearer to the average joe and jane, something like:

"this" is the undead hand of a convicted murderer, always pointing back to its traumatic origin story--except for when it doesn't. Which is all the time. Scrap that. "this" is like a compass in a world where everything is magnetic north and also ghosts are out to get you. No, that's not it.

(Also, can you tell Halloween talk is beginning to get to me?)

To sum up, "this" is a strange little word that can be very helpful once you understand what it can do--and what it can't do.

And today, with a great hour of Q&A with our Javascript instructor, I felt something click into place, as if I found a spot for "this"--that undead hand trying to crawl home, that swinging compass needle trying to orient itself.

Now if only Javascript had a "that" as well.

(Actually, it's pretty great that Javascript doesn't have a "that" because this way, if you ever need to save your context at one moment so you can call it later, you can do so by saying
that = this
which makes me so happy.)

No comments:

Post a Comment