Search code examples
javascriptoopaudioobject-literal

Create an audio element and give it properties inside an object literal


I'm trying to get out of bad habits of writing spaghetti code. I found a great tutorial on modular javascript and I'm trying to apply it to a project of mine.

I have this:

var sfx = {}

sfx.mySound1 = document.createElement('audio');
sfx.mySound1.src = 'https://some-url.ogg';
sfx.mySound1.moreProps = "...";

sfx.mySound2 = document.createElement('audio');
sfx.mySound2.src = 'https://some-url.ogg';
sfx.mySound2.moreProps = "...";

In another object I can play a sound effect like this:

sfx.mySound1.play();

I want to achieve the same thing but I want to use the object literal pattern:

const sfx = {
    mySound1: {
        // create audio element
        // give it props
    },
    mySound2: {
        // create audio element
        // give it props
    }
}

I can't seem to figure out how to create the audio element and give it properties in the same object. Maybe that defies logic and shouldn't work. If so, how should I write it instead to keep it all inside the sfx object?


Solution

  • Try this:

    var sfx = {
      mySound1: Object.assign(document.createElement('audio'), {
        src: 'https://some-url.ogg',
        moreProps: '...'
      }),
    
      mySound2: Object.assign(document.createElement('audio'), {
        src: 'https://some-url.ogg',
        moreProps: '...'
      })
    }
    

    The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object.

    Looks clear enough, but refer to Object.assign() docs for browser compatibility and polyfill.