views:

68

answers:

3

I've seen and written many javascript methods like this lately:

var myObj = {
  dialogOptions: {...},
  init: function() {
    var $this = this;
    var something = $("<div/>").load("...", null, function() {
      $(this).dialog($this.dialogOptions);
    });
  }
}

Now, this works due to the nature of closures, but the named variable reference to the particular level of scope seems awkward. My question is:

Is there some javascript operator that performs var $this = this; on the inner scope? Or, perhaps is there a way to traverse the object hierarchy to get the property I'm looking for in the inner scope?

+1  A: 

Short answer: nope.

Long answer: the "problem" is the unique nature of this in a language where everything is an object. You can't pick and choose about when this means this this or means the other this.

That's javascript for you. You can do a great deal but it ain't always pretty.

annakata
Would just like to point out that function methods call and apply can re-bind this to other objects.
Jani Hartikainen
that's true, but doesn't apply to the closure case here
annakata
+1  A: 

There is no definite way to avoid this. However, some libraries provide a way to bind functions to specific scopes - usually allowing syntax like this:

(function() { /* do something */ }).bind(whatever)

Depending on your taste this may be cleaner than declaring the scope in a separate variable. What the bind in the above context does, is essentially this:

Function.prototype.bind = function(scope) {
    var thisFunction = this;
    return function() {
        thisFunction.call(scope);
    };
};
Jani Hartikainen
+1  A: 

In this case, if myObj is a global (or globally reachable) variable, I often do the following:

var myObj = {
  dialogOptions: {...},
  init: function() {
    var something = $("<div/>").load("...", null, function() {
      $(this).dialog(myObj.dialogOptions);
    });
  }
}
Triptych
Easy to run into problems if you decide to rename the variable tho. Otherwise a decent approach I think
Jani Hartikainen
*faceplam* duh...forgot about that part. Thanks!
casademora
@Jani, for many projects, I find that a search/replace is preferable to a bunch of "var that = this" statements.
Triptych