繁体   English   中英

Function.prototype.bind,以null作为参数

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM