Неопределенная функция с javascripts

Пишу небольшой "калькулятор котировок". Я хочу распечатать сводку в браузере с помощью innerHTML, но вместо цены получаю "неопределенный". Но в моем console.info все работает отлично, я могу console.info переменную цену и получить ожидаемый результат.

//Variables 

const form = document.getElementById('request-quote');
const html = new HTMLUI();

//Event Listeners 

eventListeners();

function eventListeners() {
  document.addEventListener('DOMContentLoaded', function() {
    //Create the <option> for the years
    html.displayYears();
  });
  //when the form is submitted

  form.addEventListener('submit', function(e) {
    e.preventDefault();

    //get values from the form
    const make = document.getElementById('make').value;
    const year = document.getElementById('year').value;

    //Read the radio buttons

    const level =
      document.querySelector('input[name = "level"]:checked').value;

    // Validation
    if (make === '' || year === '' || level === '') {
      html.displayErrors('All fields are mendatory')
    } else {
      //Make the quotation
      const insurance = new Insurance(make, year, level);
      const price = insurance.calculateQuotation(insurance);
      //print
      html.showResults(price);
    }

  });
}
// Create another prototype with for the object HTMLUI. to print Errors

//Object 
// Everything related to the calculation and quotation

function Insurance(make, year, level) {
  this.make = make;
  this.year = year;
  this.level = level;
}

//calculation 

Insurance.prototype.calculateQuotation = function(insurance) {
  let price;
  const base = 2000;

  //get make
  const make = insurance.make;

  /**
   1. america: 15
   2. Asia : 5
   3. europia: 35
  */

  switch (make) {
    case '1':
      price = base * 1.15;
      break

    case '2':
      price = base * 1.05;
      break

    case '3':
      price = base * 1.35;
      break
  }

  //get level

  const level = insurance.level;

  price = this.calculateLevel(price, level);

  //get year

  const year = insurance.year;
  const difference = this.getYearDifference(year);
  price = price - ((difference * 3) * price) / 100;
  console.info(price);

}
//return difference between years

Insurance.prototype.getYearDifference = function(year) {
  return new Date().getFullYear() - year;
  // each year the cost must be 3% cheaper

}

//add value based on level

Insurance.prototype.calculateLevel = function(price, level) {
  //basic increase 30%

  //complete increases 50%
  if (level === 'basic') {
    price = price * 1.30;
  } else {
    price = price * 1.50;
  }
  return price;
}


function HTMLUI() {}
//display the latest 20 years in the select
HTMLUI.prototype.displayYears = function() {
  //Max & minimum years
  const max = new Date().getFullYear();
  min = max - 20;
  //Generate the list
  const selectYears = document.getElementById('year');

  //print the values

  for (let i = max; i >= min; i--) {
    const option = document.createElement('option')
    option.value = i;
    option.textContent = i;
    selectYears.appendChild(option);
  }
}

//Print Error, by creating a prototype

HTMLUI.prototype.displayErrors = function(message) {
  //create div
  const div = document.createElement('div');
  div.classList = 'error';

  //insert message
  div.innerText = `
    <p>${message}</p>
    `;

  form.insertBefore(div, document.querySelector('.form-group'));

  //Remove the error

  setTimeout(function() {
    document.querySelector('.error').remove();
  }, 3000);
}

HTMLUI.prototype.showResults = function(price) {
  //print result
  const result = document.getElementById('result');

  //create a div with the result

  const div = document.createElement('div');
  //insert the result
  div.innerHTML = `
    <p class = "total">Total: $ ${price}</p>
    `;
  //insert into html

  result.appendChild(div)
}

Я ожидаю напечатать значение переменной цены (которая на самом деле будет ценой), но я получаю "неопределенный" при попытке напечатать цену

Не могли бы вы дать соответствующий html, пожалуйста?

PopHip 29.05.2019 14:10
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
В JavaScript одним из самых запутанных понятий является поведение ключевого слова "this" в стрелочной и обычной функциях.
Концепция локализации и ее применение в приложениях React ⚡️
Концепция локализации и ее применение в приложениях React ⚡️
Локализация - это процесс адаптации приложения к различным языкам и культурным требованиям. Это позволяет пользователям получить опыт, соответствующий...
Улучшение производительности загрузки с помощью Google Tag Manager и атрибута Defer
Улучшение производительности загрузки с помощью Google Tag Manager и атрибута Defer
В настоящее время производительность загрузки веб-сайта имеет решающее значение не только для удобства пользователей, но и для ранжирования в...
Безумие обратных вызовов в javascript [JS]
Безумие обратных вызовов в javascript [JS]
Здравствуйте! Юный падаван 🚀. Присоединяйся ко мне, чтобы разобраться в одной из самых запутанных концепций, когда вы начинаете изучать мир...
Система управления парковками с использованием HTML, CSS и JavaScript
Система управления парковками с использованием HTML, CSS и JavaScript
Веб-сайт по управлению парковками был создан с использованием HTML, CSS и JavaScript. Это простой сайт, ничего вычурного. Основная цель -...
JavaScript Вопросы с множественным выбором и ответы
JavaScript Вопросы с множественным выбором и ответы
Если вы ищете платформу, которая предоставляет вам бесплатный тест JavaScript MCQ (Multiple Choice Questions With Answers) для оценки ваших знаний,...
3
1
61
2
Перейти к ответу Данный вопрос помечен как решенный

Ответы 2

Ответ принят как подходящий

Вам нужно добавить оператор return к функции calculateQuotation. Вот почему, если это поможет.

Причина, по которой вы получаете undefined, заключается в том, что переменной price никогда не присваивается значение.

В этой строке:

const price = insurance.calculateQuotation(insurance);

price получает то, что возвращает функция calculateQuotation с оператором return. Однако в этой функции вы просто заполняете переменную price, которая существует только в контексте этой функции. Чтобы это работало, я считаю, что вам нужно добавить оператор return в конце функции calculateQuotation следующим образом:

Insurance.prototype.calculateQuotation = function(insurance) {
  let price;
  const base = 2000;

  //get make
  const make = insurance.make;

  /**
   1. america: 15
   2. Asia : 5
   3. europia: 35
  */

  switch (make) {
    case '1':
      price = base * 1.15;
      break

    case '2':
      price = base * 1.05;
      break

    case '3':
      price = base * 1.35;
      break
  }

  //get level

  const level = insurance.level;

  price = this.calculateLevel(price, level);

  //get year

  const year = insurance.year;
  const difference = this.getYearDifference(year);
  price = price - ((difference * 3) * price) / 100;
  console.info(price);
  return price; // Added this in
}

Рад, что смог помочь!

basicallydan 30.05.2019 16:31

Он показывает неопределенную причину, по которой вы никогда не возвращали результат. Вам нужно вернуть переменную «цена», чтобы исправить это.

...
  const difference = this.getYearDifference(year);
  price = price - ((difference * 3) * price) / 100;
  console.info(price);
  return price;
}

Другие вопросы по теме