Chapter 2. this All Makes Sense Now!
In Chapter 1, we discarded various misconceptions about this and
learned instead that this is a binding made for each function
invocation, based entirely on its call-site (how the function is
called).
Call-Site
To understand this binding, we have to understand the call-site: the
location in code where a function is called (not where it’s declared).
We must inspect the call-site to answer the question: what is this
this a reference to?
Finding the call-site is generally “go locate where a function is called from,” but it’s not always that easy, as certain coding patterns can obscure the true call-site.
What’s important is to think about the call-stack (the stack of functions that have been called to get us to the current moment in execution). The call-site we care about is in the invocation before the currently executing function.
Let’s demonstrate the call-stack and call-site:
functionbaz(){// call-stack is: `baz`// so, our call-site is in the global scopeconsole.log("baz");bar();// <-- call-site for `bar`}functionbar(){// call-stack is: `baz` -> `bar`// so, our call-site is in `baz`console.log("bar");foo();// <-- call-site for `foo`}functionfoo(){// call-stack is: `baz` -> `bar` -> `foo`// so, our call-site is in `bar`console.log("foo");}baz();// <-- call-site for `baz`
Take care when analyzing code to find the actual call-site (from the
call-stack), because it’s the only thing that matters for this
binding.
Note
You can ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access