我正在学习 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);
}
最佳答案
您必须初始化对象的实例:
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 .
关于javascript 从原型(prototype)调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21387380/