Yesterday, we looked at callback functions and how they work.
Today, we're going to talk about implicit arguments, the parameters that actually get passed into those callback functions. Let's dig in!
Some examples
When you use the Element.addEventListener()
method to listen to an event, you can define an event
parameter on your callback function.
document.addEventListener('click', function (event) { console.log('the event object', event); });
When you use the Array.prototype.forEach()
or Array.prototype.map()
method, the callback function can include the current item in the array, it's index, and the array itself.
let wizards = ['Merlin', 'Gandalf', 'Radagast']; wizards.forEach(function (wizard, index, allWizards) { // ... });
These parameters are called implicit arguments.
They're automatically passed into the callback function by the method you're running, whether you define them or not. Defining them as parameters simply gives you access to use them.
How do they work?
To understand how implicit arguments work, it might be helpful to recreate a JavaScript method and see how you might implement it yourself.
Let's use the Array.prototype.forEach()
method as an example.
First, we'll create a forEach()
method on the Array.prototype
, and assign it a new function. This function will accept a callback
method as an argument.
Array.prototype.forEach = function (callback) { // ... };
Inside the function, we'll check that a callback
was provided, and that it's a function and not some other type of object or primitive.
Array.prototype.forEach = function (callback) { if (callback && typeof callback === 'function') { // ... } };
Inside our function, the this
keyword refers to the Array the function was run on (because we attached it to the prototype
).
(If you're unfamiliar with Object-Oriented Programming in JavaScript, learn more here.)
We'll use an old-school for
loop to loop through each item in our array (this
). Inside the loop, we'll run the callback
function, and pass the item (this[i]
), the index (i
), and the array itself (this
) into it as arguments.
Array.prototype.forEach = function (callback) { if (callback && typeof callback === 'function') { for (var i = 0; i < this.length; i++) { callback(this[i], i, this); } } };
This is, roughly, how methods that implement callback functions run under-the-hood.
Like this? A Go Make Things membership is the best way to support my work and help me create more free content.
Cheers,
Chris
Want to share this with others or read it later? View it in a browser.
0 Komentar untuk "[Go Make Things] How do implicit arguments in JavaScript callback functions work?"