Deep JavaScript Foundations, v3

Binding Precedence

Kyle Simpson

Kyle Simpson

You Don't Know JS
Deep JavaScript Foundations, v3

Check out a free preview of the full Deep JavaScript Foundations, v3 course

The "Binding Precedence" Lesson is part of the full, Deep JavaScript Foundations, v3 course featured in this preview video. Here's what you'd learn in this lesson:

Kyle uses a code example to delve into the order of operations of which binding rule takes precedence.


Transcript from the "Binding Precedence" Lesson

>> Kyle Simpson: What if you had a really crazy call site like line 9? On line 9, I have a new keyword, I have a workshop dot ask, so I have a context object. And I have dot bind, which under the covers of course using apply. I have three of my four rules matched on the same call site.

I am not by the way suggesting you should ever write a call site like that, but it does actually work. So why on Earth does it work, and how does it know which thing to use? If more than one rule matches a call site, what's the order of precedence?

>> Kyle Simpson: Well, there's a way that you could convince yourself or prove to yourself what the order of operations, or the order of precedence is. But I'm just gonna go ahead and simplify, and tell you, this is the order to ask those questions. So from here forward, if you ever need to ask yourself what is my thisKeyword gonna point out when this function gets invoked, this is how you determine that.

>> Kyle Simpson: The determination for the thisKeyword is, number one, was the function called with new? If so, the newly created object will be the thisKeyword.
>> Kyle Simpson: Number two, is the function called with a call or apply? And by the way dot bind is a sub of that rule because it also uses apply.

If so, the context object that is specified will be used.
>> Kyle Simpson: If that doesn't match, then number three, is the function called on a context object like workshop dot ask?
>> Kyle Simpson: If so, use that object. And if none of those three have applied, then we fall back to the default which says default to the global object except in strict mode.

That's it, just those four rules in that order, and it'll perfectly and completely answer every question that you may have about what does my thisKeyword point at?

Learn Straight from the Experts Who Shape the Modern Web

  • In-depth Courses
  • Industry Leading Experts
  • Learning Paths
  • Live Interactive Workshops
Get Unlimited Access Now