簡體   English   中英

如何在 JavaScript 中編寫 object 方法

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

我有一個不起作用的 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)

這是我的代碼:

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 中編寫 object 方法的正確方法是什么?

我已經將工作示例放在一起,以便您可以在代碼中看到它。

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