前端复习--Math.min.apply(Math,arr)写法的理解

来源:互联网 发布:teradata数据库sql命令 编辑:程序博客网 时间:2024/06/16 03:44

Math.min.apply(Math,arr) 这种方法用于求一个数组中的最小值,这令我很困惑,我不知道为甚么apply的第一个参数为什么重新传入Math对象,

《JavaScript高级程序设计》上说:为了正确设置this的值。 

这不是很好的解释,至少对于现阶段的我。

(1)顺藤摸瓜,我首先,研究了Math对象,从《Object-oriented javascript》上讲,

Math is a little different form the other built-in objects, because it cannot be used as a constructor to create objects. It is just a collection of functions and constants.

这貌似告诉我们,Math就是一个对象,min和max是它的方法,min和max接受的参数形式都是,Math.min(num1, num2, num3, ...)仅此而已。

(2)但是Math.min.apply(Math,arr) 这种奇怪的写法算什么呢?好吧,我们需要看看第二块,apply的用法。

call 和 apply的作用是什么?除了改变函数的this指向外,还有什么?---apply可以改变传递给函数参数的形式

从MDN上可以看到,这这属于apply的一种妙用


要理解的另一关键点:

apply的第一个参数,不可忽略!!!

if the method is a function in non-strict mode code, null and undefined will be replaced with the global object, and primitive values will be boxed

小结:对于普通函数fn,

function fn(arg1,arg2,arg3,...){
//....
}

fn(1,2,3)

fn.apply.(null,[1,2,3])

apply改变了参数的传入形式
















0 0
原创粉丝点击