user469652
user469652

Reputation: 51211

Purpose of this javascript, what kind of design patten it used?

    if (!window['console']) {
        window.console = {
        log: function(msg) {}
        }
    }


$(window).ready(function() {
    Site.onReady();
});



    var Site = {
        host: null,
        path: null,
        etc..

And there have var Helpers, var Site, looks pretty good, but can't understand the purpose? Anyone who knows that?

Upvotes: 1

Views: 96

Answers (3)

JustcallmeDrago
JustcallmeDrago

Reputation: 1885

if (!window['console']) {
    window.console = {
    log: function(msg) {}
    }
}

This checks to see if there's anything currently assigned to window.console already and if there's not, it assigns a custom object that has a 'log' function. This makes window.console.log usable no matter what, and if there's already a native (or earlier defined) version of the function, it will be used.

$(window).ready(function() {
    Site.onReady();
});



    var Site = {
        host: null,
        path: null,
        etc..

I have no idea what this is for, but Site is undefined at the time it is placed into the anonymous callback for $(window).ready(), which is something that should be avoided (just place the $(window).ready() below where site is defined)

As for this specific snippet:

$(window).ready(function() {
        Site.onReady();
    });

this passes an anonymous function to the $(window).ready() function, which will call it when the DOM is ready. Using an anonymous function directly avoids the need to name a function and then pass it in later.

function myFunc() { //we can use myFunc anywhere now, which may be unwanted Site.onReady(); }

$(window).ready(myFunc);

Lastly:

   var Site = {
            host: null,
            path: null,
            etc..

The var myVar = {key1:"value", key2:"other_value"}; syntax creates a new object with keys and values that can be used like this: myVar.key1 = "newValue!"

Upvotes: 3

hvgotcodes
hvgotcodes

Reputation: 120168

its defining a 'console' object literal on the window object, if it is not already there, which has a function log. This means in your code you can write

console.log('something')

even if the browser doesn't support it.

Upvotes: 0

Jason McCreary
Jason McCreary

Reputation: 72961

Looks like it initializes several global objects that are expected on the page. For example console, which is available in Firefox/Firebug for logging, but not other browsers. So by checking for existence of window['console'] and adding it when necessary, you can trust in the JavaScript code you can call console.log() without causing an error.

I assume Site, Helpers, etc all do something similar.

Upvotes: 0

Related Questions