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);

}
  • 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](http://stackoverflow.com/questions/1479319/simplest-cleanest-way-to-implement-singleton-in-javascript): `var Picture = {...};` – Jonathan Lonowski Jan 27 '14 at 17:23
  • Try new Picture.pictureArrayAdd(newPicture) Protoype stuff are accesible from function instances using 'new' – blessanm86 Jan 27 '14 at 17:24

1 Answers1

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.

DontVoteMeDown
  • 21,122
  • 10
  • 69
  • 105