CHAPTER 19 Ensuring Correct Use of Method-Borrowing


  • Elegantly borrowing a function from another object
  • Using an aspect or code contract to qualify the borrower
  • Evaluating side effects on both borrower and donor


You can find the code downloads for this chapter at reliablejavascript on the Download Code tab. The files are in the Chapter 19 download and are individually named according to the filenames noted throughout this chapter.

In the last chapter, we developed Conference.polyfills.arrayForEach, which you could use to augment the capabilities of an old-style Array that lacked a forEach function of its own. The focus was on developing forEach itself; the plugging-in to Array was trivial and carefree:

Array.prototype.forEach = Conference.polyfills.arrayForEach;

Carefree? Really?

One is reminded of the eager but untrained Luke Skywalker, who tells Jedi master Yoda, “I am not afraid.”

Yoda replies gravely, “You will be. You will be.”

What’s to be afraid of? Before you venture into the dangerous territory of method-borrowing, you must be prepared to answer three questions.

  • What does the method require of the borrowing object?
  • What effect will executing the method have on the borrowing object?
  • What might its execution do to the donor object?

Look again at Conference.polyfills.arrayForEach (with parameter-checking omitted). How would you answer those three questions?

Conference.polyfills.arrayForEach ...

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.