问题描述
我经常看到 JavaScript 的变量以美元符号开头.您何时/为什么选择以这种方式为变量添加前缀?
I quite often see JavaScript with variables that start with a dollar sign. When/why would you choose to prefix a variable in this way?
(我不是在问你在 jQuery 和其他人中看到的 $('p.foo')
语法,而是像 $name
和 这样的普通变量>$order
)
(I'm not asking about $('p.foo')
syntax that you see in jQuery and others, but normal variables like $name
and $order
)
推荐答案
jQuery 中非常常见的用途是将存储在变量中的 jQuery 对象与其他变量区分开来.
Very common use in jQuery is to distinguish jQuery objects stored in variables from other variables.
例如,我会定义:
var $email = $("#email"); // refers to the jQuery object representation of the dom object
var email_field = $("#email").get(0); // refers to the dom object itself
我发现这对编写 jQuery 代码非常有帮助,并且可以轻松查看具有不同属性集的 jQuery 对象.
I find this to be very helpful in writing jQuery code and makes it easy to see jQuery objects which have a different set of properties.
这篇关于为什么 JavaScript 变量以美元符号开头?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!