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?
Short answer: nope.
Long answer: the “problem” is the unique nature of
thisin 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.