How does .apply(Math, arrayName) work? (javascript)

后端 未结 4 1976
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-16 01:33

There is more than one stackoverflow question about how to find the min or max of an array of values in javascript. This is not that question.

I want to know why pas

4条回答
  •  时光取名叫无心
    2021-01-16 01:39

    When using .apply(), the first argument controls what the this pointer value will be set to when the function executes. In many cases, the this value is critically important. In a few cases, the this value is simply not used inside the function implementation (often referred to as a static function that does not operate on instance data). When this is not used, it doesn't matter what this is set to and therefore it doesn't matter what the first argument to .apply() is set to.

    So, in your specific case, Math.min() and Math.max() (and probably all the Math.xxx() functions) do not use the this pointer at all as they are all basically static functions that don't operate on instance data. So, it doesn't matter what it's set to and thus you can pass anything you want as the first argument to Math.min.apply() and it won't change the result of the function call.


    I would argue that one should still pass the correct value there which would be Math since that's what this will be when you do a normal:

    Math.min(x, y);
    

    So, to present the exact same situation to Math.min() as the above code when using .apply(), you would do it like this:

    var arr = [x, y];
    Math.min.apply(Math, arr);
    

    IMO, this promotes proper habits and proper thinking about what that first argument is supposed to be because it will matter in other circumstances.

    FYI, a similar issue comes up regularly with $.when.apply($, arr) in jQuery which also doesn't use the this argument in its implementation so one can call it as $.when.apply(null, arr) or even $.when.apply("foo", arr). Personally, I prefer to pass the "technically correct" argument which is the first one.

提交回复
热议问题