【问题标题】:how to call function inside object如何在对象内部调用函数
【发布时间】:2021-10-19 13:04:22
【问题描述】:

我有一个对象如下

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 是一个函数

【问题讨论】:

  • 我认为你不能(有待验证)。您应该将对象声明为类实例,以便您可以使用类似this.costPrice()
  • 您可以将 calculateProfit 设为箭头函数。 var calculateProfit = () => this.costPrice() * 0.2;
  • this 那么是对象本身吗?不知道,这很好!
  • @GuillaumeMunsch,有点像。请查看stackoverflow.com/questions/31095710/… 了解更多关于this 在箭头函数中的含义的详细信息。
  • 泰!刚刚经历了这个stackoverflow.com/a/7043822/3683576 :)

标签: javascript object


【解决方案1】:

calculateProfit 必须是箭头函数

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

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

console.log(shop.sellingPrice());

【讨论】:

  • 这行得通。但是你能解释一下为什么会这样吗?
  • 因为使用function时,this指的是window对象,而使用箭头函数时this指的是它当前的周围范围。
  • @ThatRandomDeveloper,仅供参考为什么工作this documentation中有详细解释。
【解决方案2】:

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

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

console.log(shop.sellingPrice());

【讨论】:

  • 有效,但你没有解释你做了什么或为什么它有帮助。
【解决方案3】:

尝试将这些函数更改为箭头:

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

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

console.log(shop.sellingPrice());

【讨论】:

  • 在这种情况下,this 将引用定义 shop 之前范围内的任何“this”。尝试将sellingPrice 更改为普通的function
  • 是的,在添加评论后我意识到只有calculateProfit 应该是箭头,我会解决这个问题:D
猜你喜欢
  • 2010-10-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-11
  • 1970-01-01
  • 2020-10-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多