jQuery.each implementation differs from native Array.forEach

前端 未结 3 1978
星月不相逢
星月不相逢 2020-12-09 09:11

Does anyone why is the otherwise excellent jQuery.each function is designed differently from the (now) native Array.forEach? F.ex:

         


        
3条回答
  •  攒了一身酷
    2020-12-09 09:44

    This actually got mentioned at the last jQuery conf; unfortunately I don't remember the details, but if you watch enough of the video from it I imagine you can find it (I think it was during Q&A after the keynote, but don't quote me on that). Anyhow someone (I don't think it was Resig himself, but another senior jQuery org member) basically said "jQuery has some things that we all know are problematic ("each" being one of the examples they gave) but there are millions of sites out there that now rely on that problematic behavior so we can't change it now."

    So in essence, the answer is that they made a bad decision (Resig is an INCREDIBLE programmer, but even he isn't perfect) and now everyone using jQuery has to suffer for the rest of time because the library maintains relatively high backward compatibility in new versions (and let's face it, that's a good thing: you don't want to have to re-write your whole site every time you upgrade jQuery).

    It's also worth mentioning that the Underscore library does have a each method with the same signature as the built-in each. In fact, Underscore's version actually uses the built-in version if present, for better performance, relying only its version if the browser doesn't support the built-in each. Since jQuery objects are just arrays, you can easily use them with _.each, and since Underscore has a lot of other functionality missing from jQuery it's an excellent library to complement jQuery.

提交回复
热议问题