我对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);
Run Code Online (Sandbox Code Playgroud)
任何人都可以向我解释这段代码片段的作用吗?的this是空,第二个参数是playsound函数.我不太了解以下行背后的用法.
onfilechange.bind(null, playsound)
Run Code Online (Sandbox Code Playgroud)
Zud*_*dwa 31
这可能是为了使代码更具可读性.如您所见,onfilechange接受第一个参数作为要在FileReader加载后调用的回调,第二个作为Event检索文件的对象.
没有.bind()添加事件监听器就会看起来像
document.getElementById('file')
.addEventListener('change', function(event) {
onfilechange(playsound, event);
}, false);
Run Code Online (Sandbox Code Playgroud)
随着.bind()您获得更短的代码,playsound函数将被添加到新创建的函数的参数列表中.而Event物体被附加在事件调度.
是什么.bind()(来自MDN:Function.prototype.bind()):
bind()方法创建一个新函数,在调用时,将其this关键字设置为提供的值,并在调用新函数时提供任何前面提供的给定参数序列.
因此,当您调用它时onfilechange.bind(null, playsound),它会创建并返回一个新函数,始终playsound作为第一个参数接收并使用全局上下文(因为null用作上下文),就像所有常规函数使用全局上下文一样,当您在没有new运算符的情况下调用它们而不使用.call()或apply()具有特定背景.