Search code examples
javascriptbrowserify

Browserify - Mentioning a function from the same file


I Am using browserify to do my JavaScript and I am having hard time remembering how to do this.

var account = require('./account');

module.exports = {
        start: function() {
            console.log('Logging');    
            module.music(this, 'game-bg.mp3');
        },
        music: function(arg, soundfile) {
            console.log('Playing music...');
            if (arg.mp3) {
                if(arg.mp3.paused) arg.mp3.play();
                else arg.mp3.pause();
            } else {
                arg.mp3 = new Audio(soundfile);
                arg.mp3.play();
            }
        }
};

When I run that, I get Uncaught TypeError: module.music is not a function and it never starts playing the music.

What did I have to do to make it working? I tried looking up the topics but I cannot find one mentioning multiple functions.


Solution

  • I think if you want to reference another function in an object (and you aren't making a class so no this), then it is clearer and easier to just assign what you want to export to a variable and later export that variable. Like this:

    var account = require('./account');
    
    var player = {
            start: function() {
                console.log('Logging');    
                player.music(this, 'game-bg.mp3');
            },
            music: function(arg, soundfile) {
                console.log('Playing music...');
                if (arg.mp3) {
                    if(arg.mp3.paused) arg.mp3.play();
                    else arg.mp3.pause();
                } else {
                    arg.mp3 = new Audio(soundfile);
                    arg.mp3.play();
                }
            }
    };
    
    module.exports = player;