首页 > 解决方案 > 如何在 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 中编写对象方法的正确方法是什么?

标签: javascriptobject

解决方案


我已经将工作示例放在一起,以便您可以在代码中看到它。

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);

推荐阅读