Base library code patterns I could not understand

I'm an intermediate level javascript developer, trying to understand how a great javascript developer writes his code, and I decided to start looking for the Backbone library as a starting point.

here is a code snippet for initial setup in the spine, please help me figure this out.

code1 -

(function(){ var root = this; }).call(this); 

is there any specific reason to use the call method simply with (), or is it just a coding preference, if I have to write the same code, I would do something like this.

 (function(root){ })(this); 

code2 -

  var Backbone; if (typeof exports !== 'undefined') { Backbone = exports; } else { Backbone = root.Backbone = {}; } 

now there is no definition of export in the global scope or not defined anywhere in the local scope, what is it if the block does here, if I wrote the same code, I would write

  var Backbone = root.Backbone = {}; 

code 3

 var _ = root._; if (!_ && (typeof require !== 'undefined')) _ = require('underscore')._; 

again I cannot find a definition of need anywhere in a local or global area

+7
source share
4 answers

Code Block 1

It depends on the preferences of the developer, you can write this code anyway, and, indeed, many libraries prefer your proposed style.

Code Block 2

This block is an AMD Boiler Plate block. AMD libraries provide the necessary to intercept JavaScript code into modules . In the case of code blocks, the exports object is the global standard used by the CommonJS module . If global exports missing, then the Backbone is added directly to the root object.

An interesting note to this is the fact that Backbone does not support exporting to the popular AMD RequireJS library.

Code Block 3

require is another global feature provided by AMD libraries, see above.

+7
source

In code1 call(this) , the function of the current this function is passed. In case this is done on a global scale, this is window . I think this is just preference and does not matter in this case.

require and exports provided by NodeJS (or a CommonJS compatible library), and they are part of the CommonJS specification.

+3
source

I think code 2 should protect the structure in case someone else defines an export in a global scope. Therefore, they check to see if it is not undefined by someone else, but simply reset it for an empty object.

0
source

@JonnyReeves pretty much answered all your questions. Not sure if you've seen the annotated backbone.js source code before, this would be useful for you.

http://documentcloud.github.com/backbone/docs/backbone.html

0
source

All Articles