[英]Function.prototype.bind with null as argument
我对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
是null,第二个参数是playsound
函数。 我不太了解以下行背后的用法。
onfilechange.bind(null, playsound)
这可能是为了使代码更具可读性。 如您所见, onfilechange
接受第一个参数作为在加载FileReader
后调用的回调,第二个作为用于检索文件的Event
对象。
没有.bind()
添加一个事件监听器就像
document.getElementById('file')
.addEventListener('change', function(event) {
onfilechange(playsound, event);
}, false);
使用.bind()
可以得到更短的代码,并且playsound
函数会被添加到新创建的函数的参数列表中。 Event
对象附加在事件发送上。
.bind()
作用是(来自MDN:Function.prototype.bind() ):
bind()方法创建一个新函数 ,在调用时,将其this关键字设置为提供的值,并在调用新函数时提供任何前面提供的给定参数序列。
因此,当您使用onfilechange.bind(null, playsound)
调用它时,它会创建并返回一个新函数, 始终接收playsound
作为第一个参数并使用全局上下文(因为null
用作上下文),就像所有常规函数都使用全局上下文一样,当你在没有new
运算符的情况下调用它们而不使用.call()
或apply()
和特定的上下文时。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.