首页 > js 当中apply.bind 这种用法是怎么执行的?

js 当中apply.bind 这种用法是怎么执行的?

function largestOfFour (arr) {
    return arr.map(Function.apply.bind(Math.max, null));
}

largestOfFour([[1,34],[456,2,3,44]); //[34, 456]

上面这个函数当中的Function.apply.bind 是怎样执行的,详细的过程是什么?


笔记 bind.apply


相当于这样:

function largestOfFour(arr) {
    return arr.map(function() {
        return Math.max.apply(null, arguments[0]);
    });
}

具体的难点,就在apply上了


obj.func() 可以通过 bind 处理成 obj.func.bind(obj)
现在 obj 表示 Math.max,func 表示 apply,那么上面那个 bind 式可以变成
Math.max.apply.bind(Math.max)

参考 Array.prototype.map()

所以 map 的 callback 的第 1 个参数是二维数组的元素,即里面的一维数组,可以作为 Math.max 的参数数组

由于 apply 在运行时,第1个参数是对象,第2个参数才是参数数组,而 map 会把当作参数数组的一维数组作为第 1 个参数传入,所以需要在 bind 的时候指定第1个参数,null 即可,Math 也行。

这一点参考 Function.prototype.bind()

所以绑定式要改成 Math.max.apply.bind(Math.max, null)

然后,Math.max.apply 其实是 Function.prototype.apply,而 Function.apply === Function.prototype.apply(不知道是不是所有环境都支持 Function.apply),所以上述绑定式就改成了

Function.apply.bind(Math.max, null)

【热门文章】
【热门文章】