0

Problem:

I am trying to call a class method from the onmouseover event. Apparently I have no idea what I am doing.

Expected Result:

constructor says, this.cssId = app
method1 says, this.cssId = app
method2 says, this.cssId = app

Result:

constructor says, this.cssId = app
method1 says, this.cssId = app
method2 says, this.cssId = undefined

Code:

<!DOCTYPE html>
<html>
<head>
    <meta charset='UTF-8'>
    <title>Test</title>
    <style>
        #app{
            border: 5px solid orange;
            width: 100px;
            height: 100px;
        }
    </style>
</head>
<body>
    <div id='app'>Test</div>
    <script>
        class MyClass {
            // Fields
            cssId = 'app'

            constructor() {
                console.log('constructor says, this.cssId = ' + this.cssId);
            }

            // Methods
            method2() {
                console.log('method2 says, this.cssId = ' + this.cssId);
                var appEl = document.getElementById(this.cssId);
            }
            method1() {
                console.log('method1 says, this.cssId = ' + this.cssId);
                var appEl = document.getElementById(this.cssId);
                appEl.onmouseover = this.method2;
            }
        }
        let thing = new MyClass();
        thing.method1();
    </script>
</body>
</html>

Thank you for your help.

fire_water
  • 1,261
  • 16
  • 30
  • 1
    there is [how does the this keyword work](https://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work), but there was an even more fitting, canonical dupe target for this... where was it... – ASDFGerte Mar 19 '20 at 19:21
  • Does this answer your question? [How to access the correct \`this\` inside a callback?](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback) – ASDFGerte Mar 19 '20 at 19:25

1 Answers1

-2

You were pretty close. You just ended up miss using the event listener

method1() {
                console.log('method1 says, this.cssId = ' + this.cssId);
                var appEl = document.getElementById(this.cssId);
                appEl.addEventListener('mouseover', this.method2) = this.method2;
            }
null
  • 1,924
  • 2
  • 13
  • 31