Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript code explanation of this inside event handler

Tags:

javascript

I have some JavaScript code that works as it should. However, I'm finding it a bit difficult to explain why it actually works. I hope, someone can make it clear to me. I have an object that must respond to certain events, e.g. click events. Part of the object looks like this:

Maps.Marker = function (id, data, clickEvent) {
    this.id = id;
    this.data = data;
    this.clicked = clickEvent;
};

The object is rendered in a Google map, so when the object is clicked in the map, I want to bubble the event to the clickEvent. Part of that code looks like this:

if (marker.clicked) { // click handler defined
google.maps.event.addListener(m, "click", function () { 
        marker.clicked();
});
}

Please note I've left out a lot of code here for brevity and know that it looks wrong as pasted here. The important thing is that the marker.clicked() function is invoked inside the Google Map event listener.

So, when my marker object is instantiated, it looks something like this:

var objClicked = function () {
if (this.data != null) {...}
...
}
var obj = new Maps.Marker("1", { "some object data" }, objClicked);

What I do not understand totally is how the this.data actually works in the objClicked function (I can access "some object data". Can someone please explain it to me?

like image 742
user1632306 Avatar asked Apr 28 '26 17:04

user1632306


1 Answers

The reason lies in the way of the this keyword in javascript. When you assign a function to a property inside an object and you later call this function, marker.clicked(), the this inside the function is set to whatever is on the left side of the dot, which in this case is marker.

UPDATE

Here is a more thorough explanation: http://www.impressivewebs.com/javascript-this-different-contexts/

like image 119
chrisbuchholz Avatar answered Apr 30 '26 05:04

chrisbuchholz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!