开发者

Difference _() and () in javascript

开发者 https://www.devze.com 2023-04-13 09:18 出处:网络
I\'ve been working in backbone.js and came across the following snippet of code. _(view.buttonViews).each(function(button) {

I've been working in backbone.js and came across the following snippet of code.

    _(view.buttonViews).each(function(button) {
        button.re开发者_开发技巧nder();
      });

Where view.buttonViews is an array. If I take away the _() and have

    view.buttonViews.each(function(button) {
        button.render();
      });

then I get an error that each is not a function. What does the _() add? Thanks!


I guess it is the Underscore.js library which provides the each method:

_.each(list, iterator, [context]) Alias: forEach
Iterates over a list of elements, yielding each in turn to an iterator function. The iterator is bound to the context object, if one is passed. Each invocation of iterator is called with three arguments: (element, index, list). If list is a JavaScript object, iterator's arguments will be (value, key, list). Delegates to the native forEach function if it exists.

This way, _([...]).each(...), is just another way of calling it.

BTW, it is also described in Backbone's documentation:

Backbone's only hard dependency is Underscore.js.


And FWIW, as @Jonathon already said, in general, _ is a valid variable name and in this case it contains a function. Adding parenthesis behind a function references calls that function and therefore, _() calls the function referred to by _. It is nothing special.

Besides that, parenthesis can occur as part of a function declaration or expression (function foo() {...}) or as grouping operator (var i = (20 + 1) * 2;).


Backbone is built on top of underscore, a utility library providing a lot of useful functionality that isn't native to JS but probably should be (eg things like traversing objects, array mapping, eliminating duplicate items in an array, that sort of thing).

It can be written using object-oriented or a functional style. So for instance your snippet of code could also be written thus:

_.each(view.buttonViews,function(button) {
        button.render();
      });


Backbone depends on Underscore which implements many utility functions. You can wrap an array with the _() function and use the Underscore API as demonstrated here.

Underscore implements these functions without touching the prototype, so each is not available to a regular array. However, it is callable from the object returned from the _ function, which wraps the original array.


Backbone provides functions from Underscore.js -> http://documentcloud.github.com/backbone/#Collection-Underscore-Methods

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号