Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

183
Views
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 answers
Answer question

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 Report

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!