Why do I see JavaScript variables prefixed with $?

▼魔方 西西 提交于 2019-12-03 11:59:52

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.

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!