0

So I made a JavaScript Object, which makes an element in the DOM, and what I use my methods for, is to for example play the audio, set the duration of the audio etc. However, a method that I made inside my object apparently doesn't exist. By the way, I'm new, so I don't really know what I did wrong... But here is my code:

function Audio(paramSource) {
    var object = document.createElement("audio");
    (...)
    function play() {
        object.play();
    };
    (...)
};

var myAudio = new Audio("http://tufda.net/space/limewire.mp3");
myAudio.play();

Thanks in advance :)!

2
  • 1
    What method specifically doesn't exist? FYI: the new Audio method surely already exists, and you shouldn't be overwriting it Commented Nov 23, 2016 at 14:45
  • @adeneo I was curious about the Audio.play() method, I should have probably pointed that out Commented Nov 24, 2016 at 7:44

2 Answers 2

1

Close, you need to assign it as a property to the object. Something like this:

function Audio(paramSource) {
    var object = document.createElement("audio");
    //...
    this.play = function() {
        object.play();
    };
    //...
};

A function can be declared like a variable, and for the Audio object to publicly expose it (instead of just being inside its own scope) you would simply set that variable to a property on this within that scope.

So in the above code, object is a variable internal to the scope of Audio and play is a property on Audio.

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

Comments

1

You can assign to the object the object var:

function Audio(paramSource) {
    this.object = document.createElement("audio");
    (...)
    this.play = function() {
        this.object.play();
    };
    (...)
};

var myAudio = new Audio("http://tufda.net/space/limewire.mp3");
myAudio.play();

By this way you can access to Audio.object from outside.

Comments

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.