Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

backbone library code patterns I couldn't understand

I am intermediate level javascript developer trying to understand how great javascript developer write their code and i decide to start looking into Backbone library as starting point.

here is some code snippet for initial setup in backbone please help me to make sense out of it.

code1 -

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

is there any specific reason to use call method over simply using (), or it is 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 nor it is defined anywhere in local scope then what is if block is doing here if i was writing the same code i would write

  var Backbone = root.Backbone = {};

code 3

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

again I can't find definition of require anywhere in local or global scope

like image 920
nitesh sharma Avatar asked Aug 16 '12 09:08

nitesh sharma


1 Answers

Code Block 1

This is down to developer preference, you could write that code either way and, indeed, many libraries do prefer your suggested style.

Code Block 2

This block is a take on the AMD Boiler Plate. AMD libraries provide the hooks required to split your JavaScript code into modules. In the code blocks case, the exports object is a global used by the CommonJS Module Standard. If the exports global is not present then Backbone is added to the root object directly.

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

Code Block 3

require is another global introduced by AMD libraries, see above.

like image 175
JonnyReeves Avatar answered Nov 10 '22 18:11

JonnyReeves