Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
10
rated 0 times [  12] [ 2]  / answers: 1 / hits: 18730  / 10 Years ago, fri, december 26, 2014, 12:00:00

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)

More From » javascript

 Answers
78

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.


[#68380] Tuesday, December 23, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
erinh

Total Points: 38
Total Questions: 100
Total Answers: 110

Location: Macau
Member since Mon, Nov 16, 2020
4 Years ago
;