首页 > 解决方案 > 如何在对象内部调用函数

问题描述

我有一个对象如下

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

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

console.log(shop.sellingPrice());

但这给了我以下错误

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

不知道我做错了什么,因为costPrice它是一个函数

标签: javascriptobject

解决方案


calculateProfit必须是箭头函数

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

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

console.log(shop.sellingPrice());

推荐阅读