'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.
When I try and create a class object for the DrinkItem I get a Uncaught TypeError: Assignment to constant variable
please see the code below:
JS file 1 code
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
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.
What am I doing wrong? I am using the class name DrinkItem for the const as I want it to link to the constructor.
What I want to do is create/instantiate at least 5 different DrinkItem objects inside of the menu array.
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.
Solution 1:[1]
Just the last piece of code: You are assigning a value to a 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
let test = menu.push(drinkItem)
console.log(test)
Solution 2:[2]
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
);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ingenious_Hans |
| Solution 2 | connexo |
