1

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");
Community
  • 1
  • 1
Konrad Viltersten
  • 36,151
  • 76
  • 250
  • 438
  • Check out this thread. http://stackoverflow.com/questions/205853/why-would-a-javascript-variable-start-with-a-dollar-sign – Dan Weber May 21 '16 at 21:18
  • 1
    `$newToMe = "I haven't used this way";` that is not setting anything on the jQuery global object. That is simply making a variable named `$newToMe`. To have set something on the jQuery object one would have to do something like: `$.newToMe=""` or `jQuery.newToMe` – Patrick Evans May 21 '16 at 21:22
  • Another regarding same subject: http://stackoverflow.com/questions/6209462/when-why-to-prefix-variables-with-when-using-jquery?lq=1 – Dan Weber May 21 '16 at 21:22
  • @PatrickEvans You're perfectly right. I guess it's been so rooted in a programmers' minds that once we see a dollar, we see jQuery. Even if it's not there, which becomes obvious once some savvy answer points that out, like yours did. – Konrad Viltersten May 21 '16 at 21:35

1 Answers1

1

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.

karllindmark
  • 6,031
  • 1
  • 26
  • 41
  • Oh, I got mislead by the response being in the context of jQuery. But of course, for it to be jQuery object we need to dottify in the name (*$.beep*). Otherwise it's going into *window.beep* or, rather, *window.$beep*, just as you say. – Konrad Viltersten May 21 '16 at 21:30
  • _"where-as `oldWay` won't"_ only if done inside a function/closure, if done outside them it will be on the global object – Patrick Evans May 21 '16 at 21:31