Home > Back-end >  How do I call a function inside a forEach loop inside a class method Javascript?
How do I call a function inside a forEach loop inside a class method Javascript?

Time:11-27

I have a function inside a class method that in unread when being called into a forEach loop.

// class method
Graph() {
  function setKey(key) {
    let setKeyStack = [key];
    return setKeyStack;
  }

  // forEach loop
  this.vertices.forEach((e) => {
    if (e === s) {
      const keyToAdd = this.nodeIDS   this.nodeIdCount.toString();
      e.setKey // not being called
    }
)

I tried attaching it to a this key word

this.setKey = setKey

but you cannot use the this keyword to attach variables to functions

ex: e.this.setKey(something)// not possible

CodePudding user response:

I'm not sure if I understood your question but I'll try to help :)

I believe you're trying to call a setKey method that is inside a Graph class from a forEach loop, correct? As I don't have the entire context, I tried to simplify the code and check if that works for you:

>     class Graph {
>         constructor() {}
>     
>         setKey(key) {
>             console.log(key);
>         }
>     }
>     
>     function main() {
>         let vertices = [];
>         let graph = new Graph();
>     
>         vertices.push(graph);
>     
>         vertices.forEach((e) => {
>             e.setKey('new key');
>         });
>     }
>     
>     main();

If you run this code the 'new key' will be logged, showing that the setKey method was successfully invoked inside the forEach loop. Was that what you're trying to achieve?

If you need something more specific please post your whole code! Hope that helps :)

CodePudding user response:

To call a function setKey with e as an argument, you have to do it like so:

const setKeyStack = setKey(e);
  • Related