0

Testing some code I found this problem, when I call the functions of the class Results directly, those work fine, but when I push those to an array and then I call the functions those don't work, because the this keyword is lost and the console shows the message of undefined.

class Results
{
    sum(numbers){
      let result=numbers.reduce((a,b)=>a+b);
      return result;
    }

    state(numbers){
      console.log(this);
      let result= this.sum(numbers)>0 ? "positive" : "negative";
      return result;
    }
}

function play(){
    let results=new Results(); 

    let numbers=[1,2,3,4];

    console.log(results.sum(numbers));
    console.log(results.state(numbers));

    let arrayfunctions=[];

    arrayfunctions.push(results.sum);
    arrayfunctions.push(results.state);

    arrayfunctions.forEach(funcion=>
    {
        console.log(funcion(numbers))
    });
}

2 Answers 2

2

Slight change is defining class methods.

sum(numbers) {
  let result=numbers.reduce((a,b)=>a+b);
  return result;
}

Changed to function assigned to class member variable

sum = (numbers) => {
  let result=numbers.reduce((a,b)=>a+b);
  return result;
}

class Results
{
    sum = (numbers) => {
      let result=numbers.reduce((a,b)=>a+b);
      return result;
    }

    state = (numbers) => {
      console.log(this);
      let result= this.sum(numbers)>0 ? "positive" : "negative";
      return result;
    }
}

function play(){
    let results=new Results(); 

    let numbers=[1,2,3,4];

    console.log(results.sum(numbers));
    console.log(results.state(numbers));

    let arrayfunctions=[];

    arrayfunctions.push(results.sum);
    arrayfunctions.push(results.state);

    arrayfunctions.forEach(funcion=>
    {
        console.log(funcion(numbers))
    });
}

play();

Sign up to request clarification or add additional context in comments.

1 Comment

What have you changed and why did you change it? Adding an explanation will make it more valuable for OP and future readers.
0

Several ways round this. One would be to store the name of the method in the array, rather than a reference to it (which will indeed, as you've discovered, change the this context.)

arrayfunctions = ['sum', 'state'];
arrayfunctions.forEach(method => console.log(results[method](numbers)));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.