javascript - Declaring Namespaces -


consider:

var myapp = myapp || {}; myapp.doalert = function(message) { alert(message); }; myapp.doalert("from myapp"); 

and

(function(ns) {     ns.doalert = function(message) {     alert(message); }; })(window.myapp2 = window.myapp2 || {}); myapp2.doalert("from myapp2"); 

they both work, , far can tell, same. purpose being declare namespace.

is there benefit 1 style on other?

the latter wrapping method(s) in anonymous function, 2 reasons:

  1. shorter (abbreviated) reference same thing (myapp vs ns).
  2. it's wrapped in anonymous function keep further declarations out of global scope.

usually see latter more avoid multiple modules defining common variable names (and overriding meaning).

see what purpose of wrapping whole javascript files in anonymous functions “(function(){ … })()”?


Comments

Popular posts from this blog

python - Subclassed QStyledItemDelegate ignores Stylesheet -

java - HttpClient 3.1 Connection pooling vs HttpClient 4.3.2 -

SQL: Divide the sum of values in one table with the count of rows in another -