In my javascript objects i found myself writing this:
this_object = this;
It seems it’s the only way to pass member variables to external functions…
google.maps.event.addListener(this.marker, 'click', function() {
this.info_window.setContent('Chicago marker');
this.info_window.open(this.map,this.marker);
});
That doesn’t work, I have to copy the object into a member variable and pass the new object (and replace all this with this_object)
This feels ugly. Is there a “better” or “cleaner” way, or is this my only option?
Sure there is a better method. It involves creating a function which has the
thiscontext already bound to a particular object.To have the
thiscontext refer to the current object, call thebind()method on the function and pass the required context as a parameter.This is now part of the ECMAScript standard, and if a browser does not implement it natively, it’s easy to do it yourselves.
See all questions and answers on SO related to this.