【问题标题】:error of prototype method or my misunderstanding in this task原型方法错误或我在此任务中的误解
【发布时间】:2018-08-07 10:22:18
【问题描述】:

任务

  1. 构建一个名为 Question 的函数构造函数来描述一个问题。一个问题应该包括: a) 问题本身 b) 玩家可以从中选择正确答案的答案(在此处选择适当的数据结构、数组、对象等) c) 正确答案(我会用一个数字)

  2. 使用构造函数创建几个问题

  3. 将它们全部存储在一个数组中
  4. 选择随机问题并将其与可能的答案一起记录在控制台上(每个问题都应该有一个数字(提示:为此任务的 Question 对象编写一个方法)。
  5. 使用“提示”功能询问用户正确答案。用户应输入正确答案的编号。
  6. 检查答案是否正确,并将答案是否正确打印到控制台(提示:为此编写另一种方法)

我的问题:我尝试通过 Question 本身和 question1 或 question2 等对象使用 Question 构造函数的方法,但输出只是错误:

Question.randomQuestion 不是函数

我的解决方案:

function Question(question, answers, correctAnswer) {
    this.question = question;
    this.answers = answers;
    this.correctAnswer = correctAnswer;
}

Question.prototype.randomQuestion = function(questions) {
    // random number for list
    var randomQuestion = Math.floor(Math.random() * questions.length) + 1;
    console.log(questions[randomQuestion].question)
    // output answers for random question
    for(var i = 0; i < questions[randomQuestion].answers.length; i++) {
        console.log(questions[randomQuestion].answers[i]);
    }

    return questions[randomQuestion];
};

Question.prototype.checkCorrectAnswerOfUser = function(currentObject, choiceOfUser) {
    if (choiceOfUser === currentObject.correctAnswer) console.log('Correct answer!');
    else console.log("I'm sorry, but your answer is wrong...");
};

// pass our questions
var question1 = new Question('Is JavaScript the best programming language?', ['Yes', 'No', "I Don't know"], 0);
var question2 = new Question('Who is Daniil?', ['cloudy man', 'cloudy girl'], 0);
var question3 = new Question('Who is Alin?', ['programmer', 'designer', 'photograph'], 2);
// make the array of questions
var listOfQuestions = [question1, question2, question3];
// save point to the current object in variable
var currentObject = Question.randomQuestion(listOfQuestions);

var choiceOfUser = prompt('Please select the correct answer. (Just type of number)');

【问题讨论】:

  • Question.prototype.randomQuestion(listOfQuestions)
  • 如果你想让randomQuestion像一个纯静态函数一样,你不需要放在原型上,原型在this上下文相关时使用,当然这不是纯静态函数的情况。所以,你可以做Question.randomQuestion = function

标签: javascript object constructor


【解决方案1】:

Question.prototype.randomQuestion 更改为:Question.randomQuestion

【讨论】:

    【解决方案2】:

    第 4 步中的赋值有点误导:

    选择随机问题并将其与可能的答案一起记录在控制台上(每个问题都应该有一个数字)(提示:为此任务的 Question 对象编写一个方法)。

    其实这是两个任务:

    • 从数组中选择一个随机问题
    • 将问题(带有数字)记录到控制台,并列出可能的答案

    您应该为此编写两个单独的程序。第一个(可以推广到任意数组,而不仅仅是特定的问题数组)应该是一个普通的全局函数:

    function getRandomElement(array) {
        …
        return element;
    }
    

    实际上只有第二个应该是问题的方法:

    Question.prototype.display = function() {
        … // use `this` to refer to the instance
    };
    

    你可以称它为currentQuestion.display()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-11-01
      • 2011-03-23
      • 1970-01-01
      • 1970-01-01
      • 2017-10-07
      • 1970-01-01
      • 2021-12-30
      • 2020-01-21
      相关资源
      最近更新 更多