SooDesuNe
SooDesuNe

Reputation: 10030

jQuery UI Design Pattern Question

I'm reading through the jQuery UI source code (ui-dialog specifically), I see this pattern repeated many times:

    var self = this,
        options = self.options,
        uiDialog = self.uiDialog;

What's the reasoning behind this pattern of, var self = this, something, something else

Upvotes: 9

Views: 449

Answers (2)

jAndy
jAndy

Reputation: 236162

it's just caching variables && obect propertys. This in general is considered as very good practice since object lookups come with a cost.

window.href

takes much more time than

var myhref = window.href;
myhref;

Of course you need to make the expensive call once, but all further calls to the cached variable are much much faster.

Another reason for using this pattern is to cache DOM node references for pretty much the same reasons. Accessing the DOM is one of the most expensive things you can do in Javascript (in a browser). So by caching references you just boost your code.

Upvotes: 8

polarblau
polarblau

Reputation: 17744

Assigning self helps with scope problems — the meaning of this might change throughout the script, self will always stay the reference to the instance. Common other forms are that and base.

The comma allows to write var only once in front of the variable definitions.

var self = this,
    options = self.options,
    uiDialog = self.uiDialog;

is the same as

var self = this;
var options = self.options;
var uiDialog = self.uiDialog;

Upvotes: 5

Related Questions