I got quite confused with Function.prototype.bind()
method.
function playsound(raw) { } function onfilechange(then, evt) { var reader = new FileReader(); reader.onload = function (e) { console.log(e); then(e.target.result); }; reader.onerror = function (e) { console.error(e); }; reader.readAsArrayBuffer(evt.target.files[0]); } document.getElementById('file') .addEventListener('change', onfilechange.bind(null, playsound), false);
Can anyone explain to me what this code fragment does? The this
is null and second argument is the playsound
function. I am not quite understanding the usage behind the below line.
onfilechange.bind(null, playsound)
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.
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.
bind is a method on the prototype of all functions in JavaScript. It allows you to create a new function from an existing function, change the new function's this context, and provide any arguments you want the new function to be called with.
The full syntax of bind : let bound = func. bind(context, [arg1], [arg2], ...); It allows to bind context as this and starting arguments of the function.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With