1

In one JavaScript file, the script was wrapped into this, why wrap codes into this? Any reference to this? Why define Basepage=global.Basepage?

;(function (global,$,_) {
  var Basepage=global.Basepage = Backbone.View.extend({});
}(app,jQuery,_));
hexacyanide
  • 88,222
  • 31
  • 159
  • 162
JavaScripter
  • 4,282
  • 9
  • 37
  • 45
  • These links should help you: http://stackoverflow.com/a/7145534/2287470 & http://markdalgleish.com/2011/03/self-executing-anonymous-functions/ – Joe Aug 23 '13 at 00:57
  • Read this: http://djay.net84.net/immediately-invoked-function-expression-part-2/ and this: http://djay.net84.net/immediately-invoked-function-expression-part-3/ – Yang Aug 23 '13 at 01:31

2 Answers2

1

By setting a var Basepage, Basepage will become a local variable in that function, and they don't need to write global.Basepage for any further references. Organization like this has several benefits, and I'll try to list each.

  1. Any variables inside the function will be inaccessible to other parts of the code. This is very useful if you declare a common name like var x or var element and don't want it to get mixed up with others as a global variable.
  2. Inside the function, 'app' is referred to as 'global'. Setting 'global.Basepage = Backbone.etc...' means that after that function is executed, app will have BasePage as a property.
  3. Some javascript loader-frameworks depend on this style to be able to initialize a module after all of its dependencies (like JQuery) have loaded.
Katana314
  • 8,429
  • 2
  • 28
  • 36
1

It is a method of namespacing. With this you get the effect on adding a single variable into the global namespace and you can access it to access other methods and variables.

What it is doing is self executing the function when the code is read, and when it executes, app, jQuery, and _ are passed in as variables to the function, which are what the parameters take on. global = app $ = jQuery _ = _.

This gives you a good way to encapsulate functionality without polluting the global namespace and decreases the risk over overriding variables that have the same name in your application.

Justin
  • 3,337
  • 3
  • 16
  • 27