I have run across some Javascript namespace definition. I am a little confused.
Below is a namespace definition correct?
var googletag = googletag || {};
so when you add a square bracket in the end, what does that mean?
googletag.cmd = googletag.cmd || [];
when you have a function defined after a namespace what does that mean?
var ctvAdManager = ctvAdManager || {};
(function () {
var gads = document.createElement('script');
gads.async = true;
gads.type = 'text/javascript';
var useSSL = 'https:' == document.location.protocol;
gads.src = (useSSL ? 'https:' : 'http:') +
'//www.googletagservices.com/tag/js/gpt.js';
var node = document.getElementsByTagName('script')[0];
node.parentNode.insertBefore(gads, node);
})();
please advise
This is shorthand
OR
notation. In englishMeans: "set
googletag
equal togoogletag
, but if it is not defined, setgoogletag
to an empty object.[]
is the same, just an empty array instead of an object.The function notation you used
I found this website explains it well. http://benalman.com/news/2010/11/immediately-invoked-function-expression/