Help Understanding Class functions

Am learning Javascript and trying to run some code to increase my understanding of using classes. Please find my code and comment on the last line for the assistance I need.

class MyApp {
  constructor(name) {
    this.name = name
  }

  getName() { return `${this.name}` }
}

const me = new MyApp("Prosper");

console.log(me.getName); // function getName() {...}

const func = (callback) => console.log(me.callback());

func(me.getName); // Why not printing "Prosper" here?

MyApp does not have a callback method, so trying to call me.callback() inside your func function, will result in TypeError: me.callback is not a function.

1 Like

But I expected since callback is a parameter and I passed me.getName as an argument which is a function that exists in the me object’s prototype when I called func, it would resolve to

const func = (getName) => console.log(me.getName())

Where is my logic wrong?

Yes, callback is a parameter of your func function and you did pass me.getName to it. The problem is, you did not call callback, you called me.callback and since the me instance of MyApp does not have such a method, you get this error.

OHH!, so the callback in the parameter and the callback in me.callback are not referencing the same thing?

Not at all. There is no such thing as me.callback. You would have to define it in the class for it to exist in the me instance.

1 Like

You could do:

class MyApp {
  constructor(name) {
    this.name = name
  }

  getName() { return `${this.name}` }

  func() {
    console.log(this.getName())
  }
}

const me = new MyApp("Prosper");
console.log(me.func()); // Prosper
1 Like

Hahaha, I feel so dumb and so wise at the same time now. Thank you for taking the time to explain it to me. I truly appreciate it