saiy2k
saiy2k

Reputation: 1862

javascript accessing member of a static class

I have the following in the section of my page:

<head>
    <link rel='stylesheet' href='style.css' />
    <script language='javascript' src='scripts/jquery-1.7.1.min.js'></script>
    <script language='javascript' src='scripts/NumberMaze.js'></script>
    <script language='javascript' src='scripts/GameConfig.js'></script>
    <script language='javascript' src='scripts/UIManager.js'></script>
    <script>
        $(document).ready(function() {
            var game = new NumberMaze();
        });
    </script>
</head>

GameConfig.js contains:

(function(undefined) {
    NumberMaze.GameConfig           =   function() {
        return {
            minCanvasWidth          :   320,
            minCanvasHeight         :   240,
            maxCanvasWidth          :   640,
            maxCanvasHeight         :   480,
        };
    };
})();

NumberMaze.js contains:

(function($, undefined) {
    NumberMaze          =   function() {
        console.log(NumberMaze.GameConfig.minCanvasWidth);
        console.log(NumberMaze.GameConfig);
    };
})(jQuery);

For the logs in NumberMaze.js I am getting the following output. How do I access the value of minCanvasWidth. Whats wrong with my code?

undefined
function () {
        return {
            minCanvasWidth          :   320,
            minCanvasHeight         :   240,
            maxCanvasWidth          :   640,
            maxCanvasHeight         :   480,
        };
    }

Upvotes: 1

Views: 90

Answers (1)

pimvdb
pimvdb

Reputation: 154818

As your log shows, you have a function stored in NumberMaze.GameConfig; not the actual object with data.

You have to call the function to get the object, since the function returns the object:

console.log(NumberMaze.GameConfig().minCanvasWidth);

However, why not set the object directly instead of wrapping it inside a (seemingly useless) function?

(function(undefined) {
    NumberMaze.GameConfig = {
        minCanvasWidth    :   320,
        minCanvasHeight   :   240,
        maxCanvasWidth    :   640,
        maxCanvasHeight   :   480,
    };
})();

That way, both of your logs just work.

Upvotes: 3

Related Questions