I am currently studying Javascript OOP and am having some issues retrieving an object as a return from a method.
Here is my code so far.
My Product.js class :
class Product {
reference;
name;
description;
imgPath;
price;
constructor(reference, name) {
this.reference = reference;
this.name = name;
}
setDescription(description) {
this.description = description;
return this;
}
setImgPath(imgPath) {
this.imgPath = imgPath;
return this;
}
setPrice(price) {
this.price = price;
return this;
}
}
My Catalog.js class :
class Catalog extends Array {
addProduct(product) {
this.push(product);
}
getProduct(reference) {
this.forEach(element => {
if (element.reference == reference) {
console.log(element); // this correctly logs the desired object with the 'G002' reference when called in main.js call
return element;
}
});
}
}
My main.js then creates a Catalog and fills it up with a few articles :
let catalog = new Catalog();
let data = [
['G001', 'Fender', 'master guitar', 'assets/img/imgf.jpg', 4500],
['G002', 'Cort', 'OK guitar', 'assets/img/imgg.jpg', 2000],
['G003', 'Squier', 'Cheap guitar', 'assets/img/imgc.jpg', 500]
];
data.forEach(element => {
let currentProduct = new Product(element[0], element[1]);
currentProduct.setDescription(element[2]).setImgPath(element[3]).setPrice(element[4]);
catalog.addProduct(currentProduct);
});
console.log(catalog); // Correctly logs the object with its 3 Product objs
console.log(catalog.getProduct('G002')); // Logs undefined !
In my index.html, the 3 scripts are loaded in this order, right before the closure of the <body>
<script src="./assets/js/Product.js"></script>
<script src="./assets/js/Catalog.js"></script>
<script src="./assets/js/main.js"></script>
I am at a loss at why the catalog.getProduct('G002')
method call in main.js will return undefined, as the element in the foreach loop is correctly logged when the reference matches in Catalog.js.
My guess would be that the object is destroyed as soon as the execution gets out of the foreach scope ?
How could I then get an object returned from this method call, if what I am trying to do is even possible ?