JaredCubilla
JaredCubilla

Reputation: 598

Using HTML5 Audio in Javascript Objects

When I run the following...

var obj = {
    array: ['1.mp3', '2.mp3', '3.mp3'],
    audio: new Audio(this.array[0])
};

...I get an error saying that it cannot read property '0' of undefined. However, when I run the following...

var obj = {
    array: ['1.mp3', '2.mp3', '3.mp3'],
};

var audio = new Audio(this.obj.array[0]);

...everything runs smoothly. How would I fix the first example? Am I doing something wrong with this?

Upvotes: 0

Views: 54

Answers (3)

Aayush Gaur
Aayush Gaur

Reputation: 104

Another way to do the same thing would be as follows:

var refArray = ['1.mp3', '2.mp3', '3.mp3']; var myObj = { array: ['1.mp3', '2.mp3', '3.mp3'], audio: new Audio(this.obj.array[0]); };

This does the same thing as stated in other answers, but allows you to add the audio object (as a property to the myObj) while you are defining the myObj variable.

Upvotes: 0

rabdill
rabdill

Reputation: 467

The problem is using this inside of a constructor: it's not referring to obj, it's referring to the new Audio object. You won't be able to reference it using this from inside the object like that.

Upvotes: 1

Amit Joki
Amit Joki

Reputation: 59232

How would I fix the first example? Am I doing something wrong with this?

You can't. The object is not yet created, so you can't refer to the property, using this

You can however do this

var obj = {
    array: ['1.mp3', '2.mp3', '3.mp3'],
}; // object now created
obj.audio = new Audio(this.obj.array[0]); // set the property.

Note that you can refer to this to refer to the obj inside functions, but not outside them.

var obj = {
   prop: (console.log(this), "Some value") // most probably Window but never obj
   func: function(){
      console.log(this); // obj
   }
}

Upvotes: 2

Related Questions