【发布时间】: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