most when building complex programs. I can’t count the number of times I’ve lost track of what the
this
keyword refers to after passing control around from function to function, and I’ve often found myself contorting my code in all sorts of confusing ways, trying to retain some semblance of sanity in my understanding of which variables were accessible where. In typical object-
oriented programming, we need a way of identifying and referring to the object that we’re currently working with.
this
serves the purpose admirably, providing our objects the ability to examine themselves, and point at their own properties.
This article will tackle the problem head-on, outlining definitions of context and scope, examining two JavaScript methods that allow us to manipulate context, and concluding with a deep dive into an effective solution to ninety percent of the problems I’ve run into.
Where Am I? And Who Are You?
Every bit of your JavaScript program is executed in one execution context or another. You can think of these contexts as your code’s neighborhood, giving each line an understanding of where it comes from, and who its friends and neighbors are. As it turns out, this is important information, as JavaScript societies have fairly strict rules about who can associate with whom; execution contexts are better thought of as gated communities than as open subdivisions.
We can refer to these social boundaries generally as scope, and they’re important enough to be codified in each neighborhood’s charter, which we’ll refer to as the context’s scope chain. Code within a particular neighborhood can only access variables listed on its scope chain, and prefers interaction with locals to associations outside its neighborhood.
0 Comments:
Post a Comment
<< Home