为什么我看到前缀为$的JavaScript变量? [英] Why do I see JavaScript variables prefixed with $?

查看:137
本文介绍了为什么我看到前缀为$的JavaScript变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个元问题。我在SO上看到的许多JavaScript代码片段都以美元符号前缀命名(例如, $ id 这个问题)。我不是指jQuery或其他库。我很清楚这是有效的,但在没有必要的情况下做起来似乎很尴尬。为什么人们会像这样命名他们的变量?它是否只是熟悉PHP等服务器端语言并将其转换为JavaScript代码?

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?

我认为可能是将变量识别为jQuery对象,例如,当您将选择的结果保存到变量中以便稍后消除重复选择时,但我没有看到任何一致的约定。

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.

推荐答案

从句法上讲,美元符号本身没有任何意义 - 对于解释器来说,它只是另一个字符,如 _ q 。但是很多使用jQuery和其他类似框架的人会将包含jQuery对象的变量作为前缀加上$,以便它们易于识别,因此不会与整数或字符串之类的东西混在一起。你可以通过在 jq _ 前面添加这些变量来轻松采用相同的约定,它会产生相同的效果。

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.

这篇关于为什么我看到前缀为$的JavaScript变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆