Function.prototype.apply.bind用法? [英] Function.prototype.apply.bind usages?
问题描述
我非常了解用法:
Function.prototype.bind.apply(f,arguments)
解释 - 使用
f
的原始(如果存在)bind
方法和参数
(其第一项将用作此
的上下文)
Explanation - Use the original (if exists)
bind
method overf
witharguments
(which its first item will be used as context tothis
)
此代码可用于(例如)通过带参数的构造函数创建新函数
示例:
function newCall(Cls) {
return new (Function.prototype.bind.apply(Cls, arguments));
}
执行:
var s = newCall(Something, a, b, c);
但是我遇到过这个:功能.prototype.apply.bind(f,arguments)
//单词交换
But I came across this one : Function.prototype.apply.bind(f,arguments)
//word swap
问题:
因为很难理解它的含义 - 在什么用法/场景中我会使用这段代码?
As it is hard to understand its meaning - in what usages/scenario would I use this code ?
推荐答案
这用于修复 .apply
的第一个参数。
This is used to fix the first parameter of .apply
.
例如,当您从数组中获得最大值时,您可以:
For example, when you get the max value from an array, you do:
var max_value = Math.max.apply(null, [1,2,3]);
但是你想把第一个参数固定为 null
,所以你可以通过以下方式创建一个新函数:
But you want to get the first parameter fixed to null
, so you could create an new function by:
var max = Function.prototype.apply.bind(Math.max, null);
那么你可以这么做:
var max_value = max([1,2,3]);
这篇关于Function.prototype.apply.bind用法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!