javascript - Function.prototype.bind()有大佬能给讲一下以下例子是怎么实现的么?
问题描述
返回数组中最大的数:
function largestOfFour(arr) {
return arr.map(Function.apply.bind(Math.max, null));
}
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
//[5,27,39,1001]
这个函数的传参看不懂,有大佬能详细讲解一下么,多谢
分步解析:
首先看,largestOfFour
拿到的参数是 一个数组 arr
。
使用 arr.map
方法可以拿到一个数组
这个数组是 arr
的每个元素都调用map里的函数后返回的结果的数组
(arr.prototype.map 可以参考 https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/map)
也就是,数组中每项都当做 Function.apply.bind(Math.max, null)
的参数,并且执行了,
那这个函数究竟做了什么呢?
首先我们说明 bind 函数做了什么
bind 可参考(https://developer.mozilla.org...
举个例子:
如果在全局写一个普通的函数:
function log() {
this(123)
}
当我现在执行 log 的时候:
log();
这时候会报错,Uncaught TypeError: this is not a function
,因为当前的 this 指向的是 window,了解this指向请看这里(https://juejin.im/post/59748c...。那么我们如何改变当前的this指向呢?
使用bind,
var newLog = log.bind(console.log);
那么,我log函数里的this指向的就是 console.log 啦!
所以我现在执行 newLog()
在控制台会输出 123。
说这些跟这个问题有什么关系呢?
因为,我们要让 Function.apply 的 this 指向 Math.max。
了解Function.prototype.apply 请移步到:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Function/apply。
举个例子:
在全局定义一个函数
function logUsername(sex, age) {
console.log(this.username, sex, age)
}
当前的 this 还是指向 window ,执行logUsername('男', 19)
可能不会输出名字,因为window.username 可能不存在,但是会输出 sex,age。
那我们如何修改这个函数的this呢?
除了刚刚 bind 哪种方法 还可以使用 apply
logUsername.apply({username: '小明'}, ['男', 19])
apply 接收的第一个参数是函数当前的作用域,也就是this指向哪里,第二个参数执行函数的参数,以数组进行传递。
现在我们再看这问题:
Function.apply.bind(Math.max, null)
可以理解为,我把 Function.apply
的this指向了Math.max
,所以执行Function.apply的时候,其实是执行的 Math.max.apply,并且还给Function.apply了一个第一个参数null,作为默认值。也就是说,Function.apply被执行的时候,第一个参数是null,也就是说Function.apply的this指针指向的是null,因为Math.max也不需要this指针。
当使用 arr.map
的时候, arr 数组中的每一项,其实也都是一个数组,这些数组的值分开以多个参数的形式传递给了 Math.max,相当于执行了Math.max.apply(null, 数1,数2, 数3...),返回数组中最大值。
上面的代码完全可以写成
function largestOfFour(arr) {
return arr.map((x)=>Math.max(...x));
}
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
或
function largestOfFour(arr) {
return arr.map(function (x){
return Math.max.apply(null, x)
});
}
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
这篇关于javascript - Function.prototype.bind()有大佬能给讲一下以下例子是怎么实现的么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!