Akbar Basha
Akbar Basha

Reputation: 1198

How to access the window instance in event function

I have a following code:

<html>
    <body>
        <div>
           <button id="but" >Click me</button>
        </div>
        <script>
            var ele = document.getElementById("but");
            ele.addEventListener('mousemove', myFunction);
            this.model = {
                'a': 'A',
                'b': 'B'
            }
            function myFunction(e) {
                alert(this.model.a);
            }

        </script>
    </body>
</html>

When I hover the button it throws an error because I can't access model.a. this seems to refer to the DOME element. How can I access this.model within that function?

Upvotes: 0

Views: 75

Answers (2)

Alexey Tukalo
Alexey Tukalo

Reputation: 21

<html>
    <body>
        <div>
           <button id="but" >Click me</button>
        </div>
        <script>

            this.model = {
                'a': 'A',
                'b': 'B'
            }           
            var ele = document.getElementById("but");
            ele.addEventListener('mousemove', e => alert(this.model.a));

        </script>
    </body>
</html>

'this' works in a very strange way in JavaScript, it points us to the object which call the function. I think you can use arrow function to fix it, because they have more traditional behavior with 'this'.

Upvotes: 1

Jumpa
Jumpa

Reputation: 918

You can just use the window object. So you should change myFunction to:

function myFunction(e) {
    alert(window.model.a);
}

Upvotes: 0

Related Questions