Search code examples
javascriptfunctionconstructorfunction-constructor

How can I log this function constructor value?


I work with JS in Brackets, and when I refresh this section, the value of the Carbo is correct in the console. But, when I try this in that console.log, the google console just write ,undefined'.

Why and how can i solve this problem?

Here is my lil' practice program.

var Foods = function(name, priceWithDollar, makingTimeMin) {
    this.name = name;
    this.priceWithDollar = priceWithDollar;
    this.makingTimeMin = makingTimeMin;
}

Foods.prototype.priceChangeToHUF = function() {
    console.log(this.priceWithDollar * 326);
}

var carbonara = new Foods('Carbonara', 10.91, 10);

carbonara.priceChangeToHUF();
console.log('The carbonara\'s price is ' + carbonara.priceChangeToHUF() + '.');

Thank you for the help.

Adam

!One other thing! Just right now, when I wrote these lines, something came to my mind. That value of the prototype (326) is actually not dynamic. But I have an idea. I have to write that actually value from the first google page, when i check the ,1 dollar to huf'.

How do I get started?

Thanks!


Solution

  • The issue is that your priceChangeToHUF is not returning a value. The following should work:

    Foods.prototype.priceChangeToHUF = function() {
        console.log(this.priceWithDollar * 326);
        return this.priceWithDollar * 326;
    }
    

    More information about default return values here: Does every Javascript function have to return a value?

    For your currency conversion, it'd probably be easier to fetch this value directly from an API instead of scraping it from Google results. This page has some good info: How do I get currency exchange rates via an API such as Google Finance?