[英]Why am I getting the Uncaught TypeError: Assignment to constant variable?
I am trying to create a vending machine app.我正在尝试创建一个自动售货机应用程序。 I have created a class constructor in one file and used export so that I can import that into my other js file.我在一个文件中创建了一个 class 构造函数并使用导出,以便我可以将其导入到我的另一个 js 文件中。
When I try and create a class object for the DrinkItem
I get a Uncaught TypeError: Assignment to constant variable
当我尝试为DrinkItem
创建一个 class object 时,我得到一个Uncaught TypeError: Assignment to constant variable
please see the code below:请看下面的代码:
JS file 1 code JS文件1代码
export class DrinkItem{
constructor(id, name, flavour,cost,stockAvailable){
this.id = id,
this.name = name,
this.flavour = flavour,
this.cost = cost,
this.stock = stockAvailable
}
}
JS file 2 code JS文件2代码
import { DrinkItem } from "../classes/drinkItem.js"
/****************************
* Generates an ID for task *
****************************/
const createItemId = () => `${Math.floor(Math.random() * 1000)} - ${new Date().getTime()}`.value
//array for purchased drink item
let menu = [];
/*************************************************
* Create at least 5 different DrinkItem objects *
*************************************************/
DrinkItem = new DrinkItem(
createItemId,
"Fanta",
"grape",
18,
10
);
let test = DrinkItem.push(menu)
console.log(test)
The error happens at the new DrinkItem()
bit, so maybe I am doing this incorrectly, I have looked at MDN, but it does not really explain it well, or maybe I miss understand it.错误发生在new DrinkItem()
位,所以也许我做错了,我看过 MDN,但它并没有真正解释清楚,或者我可能没有理解它。
What am I doing wrong?我究竟做错了什么? I am using the class name DrinkItem
for the const as I want it to link to the constructor.我使用 class 名称DrinkItem
作为常量,因为我希望它链接到构造函数。
What I want to do is create/instantiate at least 5 different DrinkItem objects inside of the menu array.我想要做的是在菜单数组中创建/实例化至少 5 个不同的 DrinkItem 对象。
once the 5 DrinkItem objects are created I can push that into the menu array
, but for now I am looking to see how to create the at least 1 object from the class.一旦创建了 5 个 DrinkItem 对象,我就可以将其推送到menu array
中,但现在我正在寻找如何从 class 创建至少 1 个 object。
Just the last piece of code: You are assigning a value to a class只是最后一段代码:您正在为 class 分配一个值
let drinkItem = new DrinkItem(
createItemId,
"Fanta",
"grape",
18,
10
);
Then here another error, menu is array and DrinkItem is object, push the last in the first one然后这里又报错了,menu是数组,DrinkItem是object,把最后一个推到第一个
let test = menu.push(drinkItem)
console.log(test)
Change to this:更改为:
let drinkItem = new DrinkItem( // DrinkItem variable name is already used for the class, you cannot give your instance the same variable name
createItemId(), // you want to call the function, not assign the function to DrinkItem.id
"Fanta",
"grape",
18,
10
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.