2

I trying to use the module pattern with JS. But when I call HM.init() in the console, it says undefined. It's like this.carousel doesn't exist at all. Why is that?

JS:

(function(window, $){

    var HM = (function (HM) {

        HM.init = function(){
            this.carousel.init();
        }

        return HM;

    })(HM || {});

    window.HM = HM;

    $(function(){
        console.log(HM.init()); // this doesn't work
    });


})(window, jQuery);

//Extending module (this is supposed to be in another file)
(function(window, HM, $){
    HM.carousel = {
        init: function(){
            return 'initialise HM';
        }
    }
})(window, HM, jQuery);.

Many thanks

1 Answer 1

4

The reason it prints undefined is because HM.init doesn't return anything (no return statement, so it defaults to returning undefined).

Either you want to add return before the call to this.carousel.init(), like so:

...
HM.init = function(){
    return this.carousel.init();
}
...

...or you want to use console.log instead inside your HM.carousel.init function, if you want to print 'initialise HM' to the console:

...
HM.carousel = {
    init: function(){
        return 'initialise HM';
    }
}
...

(the return value in itself isn't a good debugging tool, so it probably makes more sense to print it with console.log.)

Sign up to request clarification or add additional context in comments.

4 Comments

Thank Jonas for your response. I have updated the code but it's still doesn't work. Check out the code.
Right; the problem is that HM.init doesn't return anything. return this.carousel.init() inside HM.init should work, at least it does for me. By replacing with console.log I meant that you can change return 'initialise HM to e.g. console.log('initialise HM') (assuming it's only debugging output, and you don't actually want to return that). Sorry for the confusion :P
Thanks again, but in this project this code is meant to be the core where all other modules will be initialised, so doing return for each and every module is a bit messy. For example, a carousel module will be created as well a tab, accordion, and so on... So doing return for each of them is weird, unless I'm clueless of course.
Hence why you probably want console.log for debugging instead. The code itself works, but you think it doesn't because it prints undefined. The reason undefined is printed is simply because nothing is returned from the function you called. The string that you do return ('initialise HM') is being thrown away, since it isn't stored anywhere.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.