Why do I see JavaScript variables prefixed with $?

2019-03-24 16:53发布

问题:

This is sort of a meta-question. Many snippets of JavaScript I've seen here on SO are named with a dollar sign prefix (for example, $id on the second line of the snippet shown in this question). I'm not referring to jQuery or other libraries. I am well aware that this is valid, but it seems awkward to do when not necessary. Why do people name their variables like this? Is it just familiarity with a server-side language like PHP carrying over into their JavaScript code?

I thought perhaps it was to identify a variable as being a jQuery object, for example when you save the result of a selection to a variable in order to eliminate duplicate selections later on, but I haven't seen any consistent convention.

回答1:

Syntactically, the dollar sign itself means nothing -- to the interpreter, it's just another character, like _ or q. But a lot of people using jQuery and other similar frameworks will prefix variables that contain a jQuery object with a $ so that they are easily identified, and thus not mixed up with things like integers or strings. You could just as easily adopt the same convention by prefixing such variables with jq_ and it would have the same effect.

In effect, it is a crude sort of Hungarian notation.



回答2:

I will sometimes prefix a variable name with $ to indicate that it is a jQuery-wrapped element (most often when I'm using $(this) in a function a lot, I will assign that to $this).

Part of where the lack of convention may come from is people copy-pasting code together that uses different conventions, thus producing inconsistent code.

Also, sometimes (rarely I hope) people who program in PHP a lot will put $'s at the beginning of their variable names out of habit.



回答3:

I suspect the person in that example was just copying the jQuery pattern, or is used to PHP/Perl, without really understanding that it isn't necessary and has no special meaning.

However, I have seen [experienced] programmers use it for variable names that are reserved keywords, such as $class or $this. Or even for globals. It's really a personal preference more than anything, in that case.