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
This is down to developer preference, you could write that code either way and, indeed, many libraries do prefer your suggested style.
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.
require
is another global introduced by AMD libraries, see above.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With