Konrad Viltersten Konrad Viltersten - 1 year ago 71
jQuery Question

Is it wise to add variables to jQuery $ scope or is it polluting it?

I've just seen some dude suggest the following syntax instead of the one I'm usually (always) using.

$newToMe = "I haven't used this way";
var oldWay = "I've always use this way";

The general quality of his answer to the original question suggests that he knows stuff and isn't just horsing around. Still, it seems to me like there's a risk of polluting the scope of jQuery by doing so.

Am I right to be cautious or is it a good way of keeping my own stuff in a narrow scope? Should one combine the scopiness and precautiously use something like the following?

$myCoolStuff.thing1 = $(".ones");
$myCoolStuff.thing2 = $(".twos");

Answer Source

In terms of "jQuery scope pollutions", the two alternatives are the same. $me is just one of (of many) conventions as to how to name a variable - this one being related to distinguishing jQuery objects from regular ones.

However, worth mentioning is that (given the code above) $newToMe will be added to the global scope (and found in window) where-as oldWay won't. Why? Well, the var keyword will cause it to be restricted to its current context.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download