0

I have the following code:

var soundManager = {
    var _explode = new Audio('/Content/sounds/explosion.ogg');

    var _coin = new Audio('/Content/sounds/coin.ogg');
    this.play = function (name){
        switch(name){
            case "explosion":
                _explode.play();
                break;
            case "coin":
                _coin.play();
                break;
        }
    };
};

Chrome says I have an error on the second line, where _explode is defined. What's the syntax error? I'm trying to set it up so I can call soundManager.play(nameOfSound) to have it play an ogg file.

Thank you.

-Nick

Nikhil
  • 1,121
  • 2
  • 11
  • 27

2 Answers2

2

Just as @SayemAhmed said, your syntax to create an object literal is incorrect. And his answer is correct.

Here's my preferred way, to make _explode and _coin "true" private:

var soundManager=(function(){
  var _explode=new Audio('/Content/sounds/explosion.ogg');
  var _coin=new Audio('/Content/sounds/coin.ogg');
  return {
    play:function(name){
      switch(name){
        case "explosion":
          _explode.play();
          break;
        case "coin":
          _coin.play();
          break;
      }
    }
  };
})();

Now not only does _explode and _coin become inaccessible, but you can also get a more "compressed" size when using JS minifiers like Google Closure Compiler, because all _explode and _coin will be minimized.

Passerby
  • 9,715
  • 2
  • 33
  • 50
1

You cannot write statements that way inside an object literal. Try the following -

var soundManager = {
    _explode: new Audio('/Content/sounds/explosion.ogg'),
    _coin: new Audio('/Content/sounds/coin.ogg'),

    play: function (name){
        switch(name){
            case "explosion":
                this._explode.play();
                break;
            case "coin":
                this._coin.play();
                break;
        }
    }
}

To access this later, you can use something like the following -

soundManager.play('explosion');
soundManager.play('coint');

You can further improve your code by following @Passerby's suggestion -

var soundManager = (function () {
    var _explode = new Audio('/Content/sounds/explosion.ogg');
    var _coin = new Audio('/Content/sounds/coin.ogg');

    return {
        play: function (name) {
            switch (name) {
                case "explosion":
                    _explode.play();
                    break;
                case "coin":
                    _coin.play();
                    break;
            }
        };
    };
})();

Using closures this way, only the play method will have access to the _explode and _coin variables.

Community
  • 1
  • 1
MD Sayem Ahmed
  • 28,628
  • 27
  • 111
  • 178