Frage

Underscore.js defines aliases for functions like _.each (alias: forEach) and _.map (alias: collect) and I don't understand why.

I initially thought this was to avoid issues with browsers that didn't implement those functions natively, my thinking was that calling [].map() would throw an error in IE7 and 8 because they didn't implement it natively but found that there was no issue since Underscore already defines those.

Then I thought it could have something to do with conflicts with other JS libraries like Prototype that implement similarly named functions but then realised that having an alias doesn't actually make a difference in the case of _.map since prototype implements .map and .colelct and actually I'd been using prototype's implementation all along (eg. this.collection.collect(...)).

So far it doesn't seem to have made any difference and it hasn't created any issues but I'd really like to know why this is happening.

War es hilfreich?

Lösung

I guess the purpose of aliases is to make the library more familiar for programmers with different backgrounds (eg, collect and include are used in Ruby, fold in functional languages etc).

Also, aliases can improve readability in some cases, for example

list.select(...).reject(...)

"sounds" better than

list.filter(...).reject(...)

Andere Tipps

If you look at their documentation, you will find it pretty close to lodash library (http://lodash.com/), and jQuery's library, and also Backbone and Ruby (found in the home page).

My guess, is that both of them are made to do the same thing, one in Server (Lodash), other in Client (Underscore), and to use the same syntax, they have some methods aliases.

Also, adding some aliases is never good, since it decreases errors when writing in multiple languages.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top