CHAPTER 18 Ensuring Correct Use of call, apply, and bind
WHAT’S IN THIS CHAPTER?
- Understanding how a function’s call-site determines the value
this
will have within the function - Using
call
andapply
to explicitly specify the value this will have within a function - Using polyfills to implement language features that aren’t natively supported by a browser
- Using
bind
to permanently set the value of this in a function, regardless of its call-site details
WROX.COM CODE DOWNLOADS FOR THIS CHAPTER
You can find the wrox.com code downloads for this chapter at www.wrox.com/go/reliablejavascript
on the Download Code tab. The files are in the Chapter 18 download and individually named according to the filenames noted throughout this chapter.
Unlike classical languages such as C# and Java in which this
always references the object that “contains” the function that’s executing, the value of this
in JavaScript varies based on how a function is executed. Undisciplined use of this
has tripped up new and experienced JavaScript developers alike.
JavaScript follows a simple set of rules when determining what value this
should be bound to. We’ll review those rules in the next section to set the stage for the primary topic of this chapter: apply
, call
, and bind
, the functions that JavaScript provides as part of Function.prototype
, which allow programmers to explicitly control the value to which this
is bound.
EXPLORING HOW THIS IS BOUND
In this section, we describe the four types of ...
Get Reliable JavaScript: How to Code Safely in the World's Most Dangerous Language now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.