Function.prototype.bind with null as argument

This is probably done in order to make code more readable. As you see, onfilechange accepts first argument as a callback to be called after FileReader loaded, second as Event object for retrieving a file.

Without .bind() adding an event listener would look like

document.getElementById('file')
    .addEventListener('change', function(event) {
        onfilechange(playsound, event);
    }, false);

With .bind() you get a shorter code, and playsound function is prepended to newly created function’s arguments list. And Event object is appended on event dispatch.

What .bind() does is (From MDN: Function.prototype.bind()):

The bind() method creates a new function that, when called, has its
this keyword set to the provided value, with a given sequence of
arguments preceding any provided when the new function is called.

So when you call it with onfilechange.bind(null, playsound), it creates and returns a new function, always receiving playsound as first argument and using global context (Because null is used as context), just like all regular functions use global context, when you call them without new operator and not using .call() or apply() with specific context.

Leave a Comment