0

I have a javascript code and I added an event listener to my object. When I click it, it says my function is not defined. Here is my js code:

class Plane {
    constructor(myMap, myPos, listener) {
        this.createMarker(myMap, myPos);
        this.clickListner = listener;
    }

    createMarker(myMap, myPos) {
        var icon = {
            url: "../Images/Plane.png", // url
            scaledSize: new google.maps.Size(30, 30), // scaled size
            origin: new google.maps.Point(0, 0), // origin
            anchor: new google.maps.Point(15, 15) // anchor
        };
        this.marker = new google.maps.Marker({
            map: myMap,
            icon: icon,
            position: myPos
        });
        this.marker.addListener('click', function () { this.pressed(); }, false);
    }

    pressed() {
        this.clickListner.onClick(this);
    }
.
.
.

And I get this error when I press the marker:

Uncaught TypeError: this.pressed is not a function

Why doesn't it work?

egjlmn1
  • 324
  • 3
  • 11
  • 1
    The 'duplicated' question might not answer your question, it's correct but probably to complicated for this context. The clue is that the `this` variable is different for functions and arrow functions. Here, you pass a regular function as a callback and `this` is the HTML element that emitted the event. If you pass an 'arrow function' instead (see the answer below), `this` is the class instance and you can access `pressed`. Hope it helped (to understand your problem and the "duplicated" answer) – Andreas Dolk May 23 '20 at 22:19

1 Answers1

6

Is not using the right context, you can solve this using an arrow function

this.marker.addListener('click',() => { this.pressed(); }, false);
                                   ^
Ele
  • 33,468
  • 7
  • 37
  • 75
  • Thank you so much! It worked, just out of curiosity why what I wrote didn't work? I read that is a correct syntax as well – egjlmn1 May 24 '20 at 07:13
  • @Egjlmn1 the handler was bound with a specific context `this`, probably `this === this.marker`. So, you're trying to access the function `pressed` from `this.marker`. – Ele May 24 '20 at 09:42