0

I am learning javascript. When I call pictureArrayAdd method I receive error Picture.pictureArrayAdd is not a function. Why?

window.onload = init;
//window.picture = new Array();

function init() {
    var button = document.getElementById("addButton");
    button.onclick = addPicture;
}

function Picture() {};

Picture.prototype = {
    pictureArray: [],
    pictureArrayAdd: function(newImage) {
        this.pictureArray.push(newImage);
        return this

    }
}


var addPicture = function() {
    var textInput = document.getElementById ("pictureName");
    var newPicture = textInput.value;
    Picture.pictureArrayAdd(newPicture);

}
2
  • 1
    You'll want to create an instance: var picture = new Picture(); picture.pictureArrayAdd(...). Otherwise, you don't need a constructor if you just want a singleton: var Picture = {...}; Commented Jan 27, 2014 at 17:23
  • Try new Picture.pictureArrayAdd(newPicture) Protoype stuff are accesible from function instances using 'new' Commented Jan 27, 2014 at 17:24

1 Answer 1

3

You have to initialize an instace of your object:

var addPicture = function() {
    var textInput = document.getElementById ("pictureName");
    var newPicture = textInput.value;
    var pic = new Picture();
    pic.pictureArrayAdd(newPicture);
}

Besides - just a tip -, you can use a optional parameter on your constructor, like this:

function Picture(newImage) {
    if (newImage != undefined) {
        this.pictureArrayAdd(newImage);
    }
};

So you have a shortcut to your pictureArrayAdd function:

var pic = new Picture("picture1.png");

See it working here.

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

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.