javascript从原型调用函数

时间:2014-01-27 17:21:10

标签: javascript prototype

我正在学习javascript。当我调用pictureArrayAdd方法时,我收到错误Picture.pictureArrayAdd不是一个函数。为什么呢?

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 个答案:

答案 0 :(得分:3)

您必须初始化对象的实例:

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

除了 - 只是一个提示 - ,您可以在构造函数上使用可选参数,如下所示:

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

所以你有pictureArrayAdd功能的快捷方式:

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

看到它正常工作here