Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

188
Visualizações
how to call function inside object

I have an object as follows

var shop = {
    costPrice: function() {
        return 100;
    },
    sellingPrice: function() {
        var calculateProfit = function() {
            return this.costPrice() * 0.2;
        }

        return this.costPrice() + calculateProfit();
    }
};

console.log(shop.sellingPrice());

But this gives me the following error

objects.html:16 Uncaught TypeError: this.costPrice is not a function
    at calculateProfit (objects.html:16)
    at Object.sellingPrice (objects.html:19)
    at objects.html:22

Not sure what I am doing wrong as costPrice is a function

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

calculateProfit must be an arrow function

var shop = {
            costPrice : function() {
                return 100;
            },
            sellingPrice : function() {
                var calculateProfit = () => {
                    return this.costPrice() * 0.2;
                }

                return this.costPrice() + calculateProfit();
            }
        };

console.log(shop.sellingPrice());
about 4 years ago · Juan Pablo Isaza Relatório

0

var shop = {
    costPrice: function() {
        return 100;
    },
    sellingPrice: function() {
        var calculateProfit = () => this.costPrice() * 0.2;

        return this.costPrice() + calculateProfit();
    }
};

console.log(shop.sellingPrice());

about 4 years ago · Juan Pablo Isaza Relatório

0

Try changing these functions to be arrows:

var shop = {
            costPrice : function() {
                return 100;
            },
            sellingPrice : function() {
                var calculateProfit = () => {
                    return this.costPrice() * 0.2;
                }

                return this.costPrice() + calculateProfit();
            }
        };

console.log(shop.sellingPrice());
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda