[英]I'm getting an error of Uncaught TypeError?
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 我正在创建一个简单的测验应用程序,但我坚持使对象构造函数错误为未捕获的TypeError:Question.pushQuestion不是函数
function Question(question){
this.question = [];
}
Question.prototype.pushQuestion = function(question){
this.question.push(question);
}
var question1 = Question("is 1 = 1 ?");
Question.pushQuestion(question1);//error
var question1 = new Question("is 1 = 1 ?");
You've missed the new
keyword. 您错过了
new
关键字。
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, eg 因此,您应该使用
question1
来访问原型链中的任何方法,例如
question1.pushQuestion('How are you doing?');
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
. 因为我很确定您不想将问题本身推送到
question.list
。
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 ?"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.