javascript - 如何在 JavaScript 中编写对象方法
问题描述
我有一个不起作用的对象方法,它给了我这个错误:
buyBike: (money) => {
^^^^^^^
SyntaxError: Unexpected identifier
at wrapSafe (internal/modules/cjs/loader.js:979:16)
at Module._compile (internal/modules/cjs/loader.js:1027:27)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
at Module.load (internal/modules/cjs/loader.js:928:32)
at Function.Module._load (internal/modules/cjs/loader.js:769:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
这是我的代码:
let money = 500;
let bike = {
cost: 300
buyBike: (money) => {
if (money >= this.cost) {
money -= this.cost;
} else {
console.log("You don't have enough money to buy this bike.");
}
}
}
那么,在 JavaScript 中编写对象方法的正确方法是什么?
解决方案
我已经将工作示例放在一起,以便您可以在代码中看到它。
let money = 500;
let bike = {
cost: 300,
buyBike: function(money) {
if (money >= this.cost) {
money -= this.cost;
console.log("Sold!");
} else {
console.log("You don't have enough money to buy this bike.");
}
}
}
bike.buyBike(money);
推荐阅读
- oracle-apex - oracle apex 中未显示编辑按钮
- perl - 找不到 XML/Simple.pm
- image - 防止图像被编辑和修饰
- javascript - 我的 Get Ajax 请求中的跨域读取阻塞 (CORB) 问题
- xcode - 约束和自动布局在 Storyboard 中是如何工作的?Xcode 9
- java - BeanCreationException:创建类路径资源中定义的名称为“pgService”的 bean 时出错
- vba - 仅 Mac 上的 FileDialog 运行时 91 错误
- android - Android ViewModel 设计/架构
- android - 如果内容的高度大于屏幕,CardView 中的 ListView 不显示所有内容
- angular - 如何动态管理角度布局