Challenge: Implement Static Properties and Methods in a Class
Task
Imagine you're building an inventory management system for an online store. The Product
class needs to keep track of the total number of products added to the inventory, as well as provide functionality to compare the prices of two products.
- Define a Static Property:
- In the
Product
class, create a static propertytotalProducts
initialized to0
; - Each time a new
Product
instance is created, incrementtotalProducts
by 1 to keep track of how many products have been added to the inventory.
- In the
- Define a Static Method: Define a static method
comparePrices(product1, product2)
that takes twoProduct
instances as parameters and returns:"Product 1 is more expensive"
ifproduct1
has a higher price;"Product 2 is more expensive"
ifproduct2
has a higher price;"Both products have the same price"
if they are equal.
class Product { _____ _____ = 0; // Define static property for total products constructor(name, price) { this.name = name; this.price = price; Product._____+=1; // Increment totalProducts } // Static method to compare prices _____ comparePrices(product1, product2) { if (product1.price > product2.price) { return _____; } else if (_____ < _____) { return _____; } else { return 'Both products have the same price'; } } } // Testing const product1 = new Product('Laptop', 1200); const product2 = new Product('Smartphone', 800); const product3 = new Product('Tablet', 1200); console.log(Product.comparePrices(product1, product2)); // Expected: Product 1 is more expensive console.log(Product.comparePrices(product1, product3)); // Expected: Both products have the same price console.log(Product.comparePrices(product2, product3)); // Expected: Product 2 is more expensive console.log(Product.totalProducts); // Expected: 3
Thanks for your feedback!