-1

I'm unable to access a private method that was used as an argument for a submitted event. The use of this now points to the form rather than the class itself. what is the easiest way to reference a class irrespective of object depth or closure in javascript?

class payment {
    
    #form;
    
    constructor() {
        this.#form = $('#code-form').get(0);
        this.#form.addEventListener('submit', this.#submitForm);
    }

    
    #submitForm(e) {
        e.preventDefault(); 
        console.log( this.#form ); // Cannot read private member #form from an object whose class did not declare it
    }

}

(new payment());
Uchenna Ajah
  • 320
  • 3
  • 15
  • @MisterJojo - By the use of `addEventListener('submit', x)`, it shouldn't be too difficult to know that `$('#code-form')` is a `
    ` element!
    – Uchenna Ajah Mar 18 '23 at 22:25
  • @MisterJojo - The problem here is not about the `
    `. Even if the form contains just one submit button and nothing else, it still fulfills its purpose. There is nothing weird about the form. The problem you should be concerned about is the `this` keyword and how it can point to the `payment` class
    – Uchenna Ajah Mar 18 '23 at 22:33
  • @MisterJojo - I've edited the code! This doesn't require too many question or re-editing of code. The problem is clearly visible even from the minimal code – Uchenna Ajah Mar 18 '23 at 22:37
  • I have no imagination for this kind of thing, would you be blaming me for it? on the other hand, unlike you, I know how to use a debugger. – Mister Jojo Mar 18 '23 at 22:46
  • Instead of `'submit', this.#submitForm`, do `'submit', (e) => this.#submitForm(e)` so you retain the correct `this` context (see duplicate for more info) – Nick Parsons Mar 18 '23 at 23:30

1 Answers1

1

You can use bind in the constructor or when adding the event listener 1.

Here is an example using bind:

class payment {
    #form;

    constructor() {
        this.#form = $('#code-form').get(0);
        this.submitForm = this.submitForm.bind(this);
        this.#form.addEventListener('submit', this.submitForm);
    }

    submitForm(e) {
        e.preventDefault();
        console.log(this.#form);
    }
}

(new payment());
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Example</title>
    <script src="https://code.jquery.com/jquery-latest.min.js"></script>
</head>

<body>
    <form id="code-form">
        <button type="submit"></button>
    </form>
</body>

</html>
Vanortton
  • 51
  • 11