Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a better method than setting a variable to this?

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?

like image 653
Galen Avatar asked Aug 25 '10 23:08

Galen


2 Answers

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.

like image 194
Anurag Avatar answered Oct 05 '22 22:10

Anurag


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.

like image 32
gnarf Avatar answered Oct 06 '22 00:10

gnarf