以null为参数的Function.prototype.bind [英] Function.prototype.bind with null as argument
问题描述
我对 Function.prototype.bind()
方法非常困惑.
函数playound(raw){}函数onfilechange(then,evt){var reader = new FileReader();reader.onload =函数(e){console.log(e);然后(e.target.result);};reader.onerror =函数(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,播放声音)
这样做可能是为了使代码更具可读性.如您所见, onfilechange
接受第一个参数作为在加载 FileReader
之后调用的回调,其次作为 Event
对象来检索文件.>
没有 .bind()
的情况下添加事件侦听器的样子
document.getElementById('file').addEventListener('change',function(event){onfilechange(playsound,event);}, 错误的);
使用 .bind()
可以获得较短的代码,并且 playsound
函数位于新创建的函数的参数列表的前面.并且 Event
对象附加在事件分派上.
.bind()
的作用是(来自 解决方案
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.
这篇关于以null为参数的Function.prototype.bind的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!