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:
- shorter (abbreviated) reference same thing (
myapp
vsns
). - 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
Post a Comment