0

I'm trying to send a callback from a javascript class to its object. I haven't gotten anywhere with it.

class MyClass {
    constructor(param1, param2) {
      // trigger the callback
      this.callback();
   }
}

obj = MyClass({
    parameter1: 'test',
    parameter2: 'test',
    callback() {
        alert('callback received');
    }
});
7
  • 2
    that's not how you create instances of classes in javascript Commented Oct 19, 2022 at 10:01
  • What does that mean, "send a callback from a javascript class to its object"? Unclear what you're trying to achieve. Commented Oct 19, 2022 at 10:03
  • @JaromandaX typo, my bad. Just fixed Commented Oct 19, 2022 at 10:03
  • 1
    you're calling new MyClass with an argument, but have no parameters on constructor ... the arguments passed in new MyClass will be parameters on the constructor Commented Oct 19, 2022 at 10:04
  • 3
    this looks like there's some fundamental lack of knowledge around how classes work in JS. MDN is always a reasonably decent starting point: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… see the calcArea and accessors examples there. Commented Oct 19, 2022 at 10:06

1 Answer 1

5

You can just pass a callback function as an argument to the constructor:

class MyClass {
  constructor(callback) {
    callback();
  }
}

new MyClass(() => console.log('Called back'));

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

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.