繁体   English   中英

原型函数调用和绑定

[英]Prototype Function call and bind

有人可以解释背后的逻辑

Function.prototype.call.bind(Array.prototype.forEach);

在我阅读“ bind”函数时,将其赋予函数,该函数称为要在其中执行的对象的上下文。

但是在这种情况下,绑定接收功能。 因此,根据我的说法,这不是直观的语法。 如果我还有

 myOtherFunction.call(this)

呼叫仍然与forEach的上下文相关联吗?

Array.prototype.forEach是绑定到数组上下文的方法。 因此,您可以轻松地遍历如下数组:

 [1,2,3].forEach(function(x){ console.log(x) })

这等效于:

[].forEach.call([1,2,3],function(x){ console.log(x) })

因此,您要将[1,2,3]作为调用的当前上下文( this )传递给forEach()

什么Function.prototype.call.bind(Array.prototype.forEach); 确实是使用另一个函数( Array.prototype.forEach )作为bind变量的当前上下文来调用( callbind函数。

var forEach=Function.prototype.call.bind(Array.prototype.forEach);

意思是按字面意思说:»如果在forEach上进行了函数调用,请在调用它时像在Array.prototype.forEach上下文中那样调用它。«这是[].forEach.call(this,function)的快捷方式[].forEach.call(this,function)

有关更多参考,请参见Function.prototype.call()Function.protoype.bind()上的MDN。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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