简体   繁体   English

如何在 JavaScript 中编写 object 方法

[英]How can I write an object method in JavaScript

I have an object method that doesn't work and it's giving me this error:我有一个不起作用的 object 方法,它给了我这个错误:

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)

This is my code:这是我的代码:

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.");
        }
    }
}

So, what is the right way to write an object method in JavaScript?那么,在 JavaScript 中编写 object 方法的正确方法是什么?

I've put together the working example so you can see it in code.我已经将工作示例放在一起,以便您可以在代码中看到它。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM