Why are jQuery's callback arguments inconsistent?

后端 未结 4 1117
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-14 07:21

A common pattern within jQuery is a method that takes a callback which is passed an element of an array and its index within that array. However, it seems completely random

4条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-14 08:20

    It is not totally random. Because :

    $.map( $('selector'), function(el, index) { /* element (DOMElement) is first, index optional */ } );
    $('selector').map(function(index) { /* 'this' (DOMElement) is first.... index optional */ });
    

    See the pattern? The second example has a second argument, but it is only passed by convenience, and it is the same as this.

    The pattern is that the first argument is always "more" important than the second, and the last argument should be the least important (the "more optional"). So you don't need to specify all the least important arguments if you only need one. And in the case of $(...).each, often you won't even need any argument, because this is only what you want.

提交回复
热议问题