1

I have a class that take in a function as a constructor parameter. Then I have class function that calls that function later on. The problem is that the function become undefined later on. I am not sure what is happening? Is it even doable? I double check and the saveFunction property is not being re-assign else where.

class myClass {
   constructor(saveFunction ) {
      this.saveFunction = saveFunction;
      console.log(typeof this.saveFunction); // --> return function
   }

   saveClassData(saveData) {
      console.log(typeof this.saveFunction); // --> return undefined
      this.saveFunction(saveData);
   }
}
Syscall
  • 19,327
  • 10
  • 37
  • 52
Jack Thor
  • 1,554
  • 4
  • 24
  • 53
  • 4
    Please post a [mcve]. You can use a [Stack Snippet](https://meta.stackoverflow.com/questions/358992/ive-been-told-to-create-a-runnable-example-with-stack-snippets-how-do-i-do) to make it executable. – Barmar Apr 16 '21 at 20:11
  • Please provide a [mcve] of where/how you instantiate the class and call `saveClassData` so that it logs `undefined`. Surely you must be overwriting or deleting the property somewhere, maybe without noticing, or calling the method on a different object that doesn't have the property. – Bergi Apr 16 '21 at 20:11
  • Properties don't become undefined by themselves. The fact that it holds a function is irrelevant. – Barmar Apr 16 '21 at 20:12
  • 2
    Maybe (most likely?) a duplicate of [How to access the correct `this` inside a callback?](https://stackoverflow.com/q/20279484/1048572) – Bergi Apr 16 '21 at 20:12
  • Can we see how you're calling `saveClassData`? – Gershom Maes Apr 16 '21 at 20:16
  • @Bergi Bingo you're right I was referencing the wrong this. SMH thanks. – Jack Thor Apr 16 '21 at 20:20
  • Odds are you're calling saveClassData incorrectly. If you're initializing an object and calling saveClassData from that object there is no issue. – Sam Apr 16 '21 at 20:20
  • Btw, save yourself the headache and pass `this.saveFunction` as the callback directly, not the `this.saveClassData` method. – Bergi Apr 16 '21 at 20:23

1 Answers1

0

This works:

let myfunc = (logString) => console.log(logString);
let myClassVariable = new myClass(myfunc);

myClassVariable.saveFunction("walk below the shadow")

Output:

function
walk below the shadow
rustyBucketBay
  • 4,320
  • 3
  • 17
  • 47