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 this
context already bound to a particular object.
To have the this
context refer to the current object, call the bind()
method on the function and pass the required context as a parameter.
google.maps.event.addListener(this.marker, 'click', function() {
this.info_window.setContent('Chicago marker');
this.info_window.open(this.map,this.marker);
}.bind(this)); // <-- notice we're calling bind() on the function itself
This is now part of the ECMAScript standard, and if a browser does not implement it natively, it's easy to do it yourselves.
if (!Function.prototype.bind) {
Function.prototype.bind = function () {
var fn = this,
args = Array.prototype.slice.call(arguments),
object = args.shift();
return function () {
return fn.apply(
object, args.concat(Array.prototype.slice.call(arguments))
);
};
};
}
See all questions and answers on SO related to this.
It's actually a pretty common pattern when dealing with JavaScript to store a reference of this
in a local variable i.e. var myThing=this;
. Remember functions have access to local variables defined in their scope. Any variables defined in the containing functions are accessible.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With