代码改变世界

[].forEach.call()

2021-04-10 16:37  ੯ੑ·ʔ  阅读(245)  评论(0)    收藏  举报

要想明白[].forEach.call()这种写法,需要了解以下两点:

  1. foreach() 是数组的方法,只有数组才能调用,forEach()可以接受一个function作为参数;

  2. call()的使用一般是为了改变this的值;

    call()的语法:

    function.call(thisArg, arg1, arg2,...)

    thisArg:可选的,在function函数运行时使用的this的值。

    arg1, arg2, ...:指定参数列表

[].forEach.call(),可以看作

let fun = [].forEach;
fun.call();
// 第一行代码只是为了调用数组的 forEach 方法,
// [].forEach 等同于 Array.prototype.forEach

举例:[].forEach.call(list, fun)这个意思就是,将list使用forEach来遍历,fun作为参数传入forEach方法中,fun中的this也指向了list