For the More Curious: Setting this in forEach’s Callback

We told a small fib earlier. Using bind is not the only way to set the value of this for the callback to forEach.

Look at the documentation for Array.prototype.forEach on MDN (developer.mozilla.org/​en-US/​docs/​Web/​JavaScript/​Reference/​Global_Objects/​Array/​forEach). You can see that forEach takes an optional second argument, which it will use as the value of this in the callback.

That means that you could have also written the printOrders method like so:

... Truck.prototype.printOrders = function () { var customerIdArray = Object.keys(this.db.getAll()); console.log('Truck #' + this.truckId + ' has pending orders:'); customerIdArray.forEach(function (id) { console.log(this.db.get(id)); ...

Get Front-End Web Development: The Big Nerd Ranch Guide 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.