How to pass instance of a class to a method of another class as its parameter?

14 hours ago 2
ARTICLE AD BOX

I can see many issues in your code. First, let me show the correct syntax:

"use strict"; const projectStatus = { PENDING: {description: "Pending Execution"}, SUCCESS: {description: "Executed Successfully"}, FAILURE: {description: "Execution Failed"} }; class ProjectIdea { status = projectStatus.PENDING; constructor(title, description) { this.title = title; this.description = description; } updateProjectStatus(newStatus) { this.status = newStatus; } } class ProjectIdeaBoard { #ideas = []; // this member is private, accessed only // via pin, unpin, and a read-only property count constructor(title) { this.title = title; } // note, there is no pin and unpin, // they are the properties added in constructor pin(projectIdea) { this.#ideas.push(projectIdea); } unpin() { return this.#ideas.pop(); } get count() { // property getter return this.#ideas.length; } // ... } // test const idea = new ProjectIdea("my title", "my description"); const board = new ProjectIdeaBoard("my board"); board.pin(idea); console.log(board.count); const sameIdea = board.unpin(); console.log(`Title: ${sameIdea.title}; Description: ${sameIdea.description}`);

This is only one of the possible solutions. Please see the comments to the relevant code lines.

Note that #ideas is a priavate member. This is a new class feature. You can read about private members in JavaScript classes. Hiding some implementation objects is important enough. In the code snippet shown, the array object ideas is exposed only via the functions pin and unpin, and the length is exposes via the read-only property count. This way, the user cannot accidentally assign ideas to null or to the object of a wrong type.

Now, please understand how an instance function is called. Let's look at the call in the test:

board.pin(idea);

Here, the instance of the class ProjectIdeaBoard implementing pin is board. This is actually a hidden function argument passed to it and acceptable in the implementation of а function as this. If this is not used, there is no need to use function, because in this case, an arrow function can be used instead.

Pay attention for the property getter syntax using the keyword get. For the setter, the keyboard is set, and the function should accept one argument to be assigned when the property is assigned to a value.

Read Entire Article