javascript Function.prototype.bind 以 null 作为参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27654149/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Function.prototype.bind with null as argument
提问by Shane
I got quite confused with Function.prototype.bind()
method.
我对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);
Can anyone explain to me what this code fragment does? The this
is null and second argument is the playsound
function. I am not quite understanding the usage behind the below line.
任何人都可以向我解释这个代码片段的作用吗?的this
是空,第二个参数是playsound
函数。我不太了解下面这行背后的用法。
onfilechange.bind(null, playsound)
回答by Zudwa
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.
这样做可能是为了使代码更具可读性。如您所见,onfilechange
接受第一个参数作为FileReader
加载后调用的回调,第二个参数作为Event
检索文件的对象。
Without .bind()
adding an event listener would look like
不.bind()
添加事件侦听器看起来像
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.
有了.bind()
更短的代码,playsound
函数就会被添加到新创建的函数的参数列表中。并且Event
对象附加在事件调度上。
What .bind()
does is (From MDN: Function.prototype.bind()):
什么.bind()
是(来自MDN: Function.prototype.bind()):
The bind() method creates a new functionthat, 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.
bind() 方法创建一个新函数,该函数在调用时将其 this 关键字设置为所提供的值,并在调用新函数时在任何提供的参数之前提供给定的参数序列。
So when you call it with onfilechange.bind(null, playsound)
, it creates and returns a newfunction, alwaysreceiving 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.
因此,当您使用 调用它时onfilechange.bind(null, playsound)
,它会创建并返回一个新函数,始终playsound
作为第一个参数接收并使用全局上下文(因为null
用作上下文),就像所有常规函数都使用全局上下文一样,当您在new
不使用运算符而不使用的情况下调用它们时.call()
或apply()
具有特定上下文。