Javascript 参数为null的Function.prototype.bind
我对Javascript 参数为null的Function.prototype.bind,javascript,Javascript,我对Function.prototype.bind()方法感到非常困惑 function playsound(raw) { } function onfilechange(then, evt) { var reader = new FileReader(); reader.onload = function (e) { console.log(e); then(e.target.result); }; reader
Function.prototype.bind()
方法感到非常困惑
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);
谁能给我解释一下这个代码片段的作用吗?this
为空,第二个参数是playsound
函数。我不太明白下面这行后面的用法
onfilechange.bind(null, playsound)
这样做可能是为了使代码更具可读性。如您所见,
onfilechange
接受第一个参数作为在加载FileReader
后调用的回调,第二个参数作为用于检索文件的Event
对象
如果没有.bind()
添加事件侦听器
document.getElementById('file')
.addEventListener('change', function(event) {
onfilechange(playsound, event);
}, false);
使用.bind()
可以得到较短的代码,playsound
函数在新创建的函数的参数列表前面。并且Event
对象附加在事件分派上
.bind()
所做的是(从):
bind()方法创建一个新函数,该函数在调用时具有
此关键字设置为提供的值,并具有给定的
调用新函数时,将在任何函数前面提供参数
因此,当您使用
onfilechange.bind(null,playsound)
调用它时,它会创建并返回一个新的函数,始终接收playsound
作为第一个参数并使用全局上下文(因为null
用作上下文),就像所有常规函数使用全局上下文一样,当您在不使用new
运算符的情况下调用它们,并且不使用带有特定上下文的.call()
或apply()
时。事件对象附加在事件分派手段上??当不通过时,我们如何获取事件对象作为参数。当调用.bind()
时,它返回一个函数,而不是它的结果,因此该函数可以在将来使用(在您的情况下,在事件分派时)<代码>事件对象由浏览器传递。