Challenge with Object Constructors in JavaScript ES6

Embarking on an advanced React course has me tackling some preliminary tasks.

The task description lacks clarity on the expected outcome, leaving me uncertain about my results.

The task:

Part 1

To begin, create a constructor for object Client with the argument name.

This object should have attributes such as name, orders (an array to store orders), and a method addOrder(order) (to add new orders to orders)

Part 2

Next, construct a constructor for object Order with arguments client and number.

This object should possess characteristics like client (related to the client) and number (order number)

Part 3

Verify your code by testing it with the following script:

const client1 = new Client("John");
const order1 = new Order(client1, "1");
const order2 = new Order(client1, "2");

client1.addOrder(order1);
client1.addOrder(order2);

console.table(client1.orders);

Upon reviewing my own code:

class Client {
  constructor(name) {
    this.name = name;
    this.orders = [];
  }

  addOrder(order) {
    this.orders.push(order);
  }
}

class Order extends Client {
  constructor(client, number) {
    super(client);
    this.number = number;
  }
}

const client1 = new Client("John");
const order1 = new Order(client1, "1");
const order2 = new Order(client1, "2");

client1.addOrder(order1);
client1.addOrder(order2);

console.table(client1.orders);

The output displayed (which I suspect is incorrect, given that name should be "John" and orders arrays should not exist):

Array(2)
0: Order {name: Client, orders: Array(0), number: '1'}
1: Order {name: Client, orders: Array(0), number: '2'}

View Console Result

Answer №1

Client should not be a subclass of Order. A client has a collection of orders, and an order has a specific client associated with it, but they are not related in terms of inheritance.

The relationship between them is implemented through a property assignment, where you simply assign the client to the order object like this: this.client = client; inside the Order constructor.

class Client {
  constructor(name) {
    this.name = name;
    this.orders = [];
  }

  addOrder(order) {
    this.orders.push(order);
   }
}

class Order {
  constructor(client, number) {
    this.client = client;
    this.number = number;
  }
}

const client1 = new Client("John");
const order1 = new Order(client1, "1");
const order2 = new Order(client1, "2");

client1.addOrder(order1);
client1.addOrder(order2);

console.log(client1.orders);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Create a div element that can be expanded on smaller devices

Is it possible to expand a div while hovering on a small or x-small device? I want to achieve something like this: https://i.sstatic.net/doJKa.png Currently, I can only hide the yellow div when the page is displayed on a small device. I am looking for a ...

How can I maintain focus selection while replacing HTML with text in a contenteditable div without losing it?

When working with a div tag that needs to be editable, the goal is to prevent users from entering any HTML into the tag. However, despite efforts to restrict input, when users copy and paste content, it often includes unwanted tags. To address this issue, ...

Eliminate the final comma from a two-dimensional array by utilizing a for loop

Is there a way to prevent the final comma from being printed? public void displayArrayMethod(int array[][]) { for(int row=0; row<array.length; row++) { for(int column=0; column<array[row].length; colu ...

The initial setTimeout function functions correctly, however the subsequent ones do not operate as expected

I have developed the following code: bot.on('message', message=> { if(message.content === "come here") { message.channel.send('hey'); setTimeout(() => { message.channel.send('i am here' ...

How to center a div both vertically and horizontally when height is not specified?

Is it possible to center a div on a webpage without specifying a fixed height, so that the height adjusts dynamically based on the content? I am willing to consider JS/jQuery solutions with fallback options but would prefer a pure CSS approach. Currently, ...

Unable to log out when the button is clicked

I am having trouble figuring out why I can't log out when clicking the button. I have a logout button in my header (navigation). My experience with React is limited. Within my project folder, I have a Store directory which contains an Auth-context f ...

What is the best way to add a value to the value attribute of a div using JavaScript?

Is there a way to insert a value into the value attribute of a div using Internet Explorer 9? I have attempted various JavaScript functions, but so far I can only modify the content inside the div and not the value attribute itself. <div id="mydiv" val ...

What are the steps for generating a diagram using Chart.js?

I'm attempting to use Chart.js to create a specific diagram. Current Challenges: The point on the x-axis should be centered within the categories. I would like the value to appear above the point. https://i.sstatic.net/FFFr1.png This is what my co ...

Having Trouble with $.ajax Function in my Program

After spending three days experimenting with various methods, I'm still unable to successfully use the Javascript ajax command to send form values to a php script. Despite no errors being displayed and the scripts running smoothly, nothing is getting ...

Using jQuery to create a draggable element with a visual indicator that represents a link between two items

Utilizing the "parenting" tool in Adobe AfterEffects allows you to connect layers together. Simply click and hold the icon, then drag it to its destination. A line is drawn from the parent layer to your cursor as a visual guide. I have mastered draggable/ ...

Discovering elements that are not equal to zero within an array

My goal is to create a piece of code that will display a print statement when a nonzero number is detected in an array. Here's my current attempt: if numpy.where(array != 0): print "NonZero element detected!" elif numpy.where(array == 0): p ...

Change a Vue route parameter from title to id

As I develop a course website, each course is assigned its own page URL. For example, when accessing course number 1, the link appears as http://localhost:8080/course/1 . However, I aim to customize it to display as http://localhost:8080/course/course-name ...

ajax is providing identical data when called too frequently

Using my barcode scanner triggers the function below, but scanning multiple barcodes quickly results in duplicate data being processed. The issue seems to be related to the async setting - when it's false, the process slows down significantly. Is the ...

Having trouble getting the "save adjustments" button to become enabled after using the jQuery datepicker

It's puzzling that my code doesn't respond to the selection of a date using the jQuery date picker to re-enable the "save changes" button. Interestingly, changing values in other input boxes seems to work perfectly fine. I'm struggling to gr ...

Challenges related to using the require() method in JavaScript

I've been encountering an issue while trying to run the JavaScript client for the Tumblr API from their Github repository. The error message I keep getting is "require not defined" which has led me on a hunt across various forums and websites, includi ...

What is the best way to use setInterval with multiple objects?

Subject: Here is an example of JavaScript code: var User = function(data){ this.name = data.name; this.delay = data.delay; this.say(); } User.prototype.say = function(){ _self = this; setInterval(function(){ console.log(_self.name); }, t ...

Unusual performance issues observed in a flexbox when adjusting window size in mobile Chrome

Encountering an unusual issue with flexbox on a mobile browser. For a visual demonstration, view this gif Specifically happening on Chrome mobile on a Google Pixel phone. Using a resize script to adjust element sizes due to limitations with 100vh: windo ...

The HTML table is failing to display

I have a CSV file called travelq.csv and I'm attempting to automatically generate a table from the data it contains. The h1 heading is loading, but unfortunately, the table is not displaying as expected. I am unsure of where I may have made a mistake ...

The onsubmit function is not successfully executing the JavaScript function

This code contains a form for creating a new user login. Upon pressing the 'continue' button, it is supposed to call the 'validateForm()' function which checks the values entered in the form. However, even when there are errors such as ...

Is there a way to configure multiple entry points in a package.json file?

I am looking to execute various commands using npm: "scripts": { "v1": "node v1.js", "v2": "node v2.js" } I would like to use npm start v1 or npm start v2 for this purpose, however, these commands do not seem to trigger the intended Node command. ...