javascript - 如何在对象内部调用函数
问题描述
我有一个对象如下
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
它是一个函数
解决方案
calculateProfit
必须是箭头函数
var shop = {
costPrice : function() {
return 100;
},
sellingPrice : function() {
var calculateProfit = () => {
return this.costPrice() * 0.2;
}
return this.costPrice() + calculateProfit();
}
};
console.log(shop.sellingPrice());
推荐阅读
- excel - 在 Excel 上按 id 列的行
- php - 日期未在控制台中显示为字符串
- javascript - 关闭一个 div - javascript 不工作
- python - Python 只有整数、切片...和整数或布尔数组是有效的索引
- html - 列排序引导程序
- python - 当我尝试接受用户输入时,我不断收到以下错误 - ValueError: invalid literal for int() with base 10: ''
- python - 创建 pd.read_csv 对象后替换值
- android - 如何使用 RecyclerView 在 ListView 中更改播放/暂停音频图标?
- postgresql - 在 plpgsql 中包含 IF.. ELSE 条件并生成动态查询
- r - 计算分组百分比