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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 07:47:45  来源:igfitidea点击:

Function.prototype.bind with null as argument

javascript

提问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 thisis null and second argument is the playsoundfunction. 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, onfilechangeaccepts first argument as a callback to be called after FileReaderloaded, second as Eventobject 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 playsoundfunction is prepended to newly created function's arguments list. And Eventobject 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 playsoundas first argument and using global context (Because nullis used as context), just like all regular functions use global context, when you call them without newoperator and not using .call()or apply()with specific context.

因此,当您使用 调用它时onfilechange.bind(null, playsound),它会创建并返回一个函数,始终playsound作为第一个参数接收并使用全局上下文(因为null用作上下文),就像所有常规函数都使用全局上下文一样,当您在new不使用运算符而不使用的情况下调用它们时.call()apply()具有特定上下文。