如何在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);