O'Reilly logo

Reliable JavaScript: How to Code Safely in the World's Most Dangerous Language by Seth Richards, Lawrence Spencer

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 and apply 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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required