0

So I'm trying to keep my javascript project organised by using classes and an init function, now I'm having this weird problem I never have experienced before. This is my code:

class App {
    constructor() {
        this._username;
    }

    authenticate() {
        this._username = "test";
    }

    submitForm() {
        console.log(this._username);
    }
}

const init = function () {
    const app = new App();

    document.getElementById("authenticationVerify").onclick = app.authenticate;
    document.getElementById("btnSendSMS").onclick = app.submitForm;
}

window.onload = init;

And HTML (simplified)

<body>
    <main>
        <form id="formSendSMS">
            <input type="button" name="send" id="btnSendSMS" value="Versturen">
        </form>

        <div id="authentication-prompt">
            <form>
                <input type="button" name="login" id="authenticationVerify" value="Log in" class="button blue">
            </form>
        </div>
    </main>
    <script src="js/mainBack.js" type="text/javascript"></script>
</body>

</html>

As you can see in the console, I get "undefined" when I activate the second button press, but I really don't know why this is happening, since the 'app' is not getting redeclared.

'undefined' in console

Kind regards, Jasper

2
  • can you please share HTML code? Commented Jul 26, 2021 at 13:42
  • Does matter that much I think, but yea comming up Commented Jul 26, 2021 at 13:49

1 Answer 1

1

That is not a proper way to catch click event. From your js code, I have succeeded to make a working example.

Also, JS functions cant be called without parentheses. A great example is given here.

class App {
    constructor() {
        this._username;
    }

    authenticate() {
        this._username = "test";
    }

    submitForm() {
        console.log(this._username);
    }
}

const init = function () {
    const app = new App();

 
    document.getElementById("authenticationVerify").onclick = function(e){app.authenticate()};
    document.getElementById("btnSendSMS").onclick = function(e){app.submitForm()};
}


window.onload = init;
<button id="authenticationVerify">AUTH</button>
<button id="btnSendSMS">SMS</button>

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

1 Comment

Yea I just figured it out that I shouldn't directly call the app function from the onclick function from the button. Thanks for the help. And PS: I used method refrence to link the method that's why there aren't any parentheses

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.