midnightcoder
midnightcoder

Reputation: 5

javascript calling the function from prototype

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

}

Upvotes: 0

Views: 52

Answers (1)

DontVoteMeDown
DontVoteMeDown

Reputation: 21475

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.

Upvotes: 3

Related Questions