Reputation: 336
I am creating a simple quiz app but I am stuck at making an object constructor the error is Uncaught TypeError: Question.pushQuestion is not a function
function Question(question){
this.question = [];
}
Question.prototype.pushQuestion = function(question){
this.question.push(question);
}
var question1 = Question("is 1 = 1 ?");
Question.pushQuestion(question1);//error
Upvotes: 2
Views: 50
Reputation: 63514
It looks like you're trying to generate a list of questions. I would approach like this:
function QuestionList() {
this.questions = [];
this.counter = 0;
}
QuestionList.prototype.pushQuestion = function (question) {
this.questions.push(question);
}
var questionList = new QuestionList();
questionList.pushQuestion("is 1 = 1 ?");
questionList.pushQuestion("is 1 = 2 ?");
questionList.questions // [ "is 1 = 1 ?", "is 1 = 2 ?" ]
You can then write a new method to get the next question in the list:
QuestionList.prototype.getNextQuestion = function (question) {
return this.questions[this.counter++];
}
questionList.getNextQuestion(); // "is 1 = 1 ?"
questionList.getNextQuestion(); // "is 1 = 2 ?"
Upvotes: 1
Reputation: 7369
When you define a function on an object prototype, you can invoke it by calling the function on a new-ed up instance of that object.
function Question(question){
this.question = [];
}
Question.prototype.pushQuestion = function(question){
this.question.push(question);
}
var question1 = new Question("is 1 = 1 ?");
question1.pushQuestion(question1);
What are you trying to achieve? Because I'm pretty sure you don't want to push the question itself into question.list
.
Upvotes: 1
Reputation: 5971
var question1 = new Question("is 1 = 1 ?");
You've missed the new
keyword.
Also, here you create instance of your object:
var question1 = Question("is 1 = 1 ?");
So, you should use question1
in order to access any method from prototype chain, e.g.
question1.pushQuestion('How are you doing?');
Upvotes: 4