Javascript 何时/为什么在使用 jQuery 时为变量加上“$”前缀?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6209462/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
When/why to prefix variables with "$" when using jQuery?
提问by elclanrs
Possible Duplicate:
Why would a javascript variable start with a dollar sign?
I see people using the dollar sign in front of variables when using jQuery. Is there any reason behind this? I'm I missing something basic or is it just a common practice?
我看到人们在使用 jQuery 时在变量前使用美元符号。这背后有什么原因吗?我错过了一些基本的东西还是只是一种常见的做法?
回答by Scott Harwell
It's a common reference to a jQuery wrapped object. It makes reading the code easier to know which variables are jQuery wrapped.
它是对 jQuery 包装对象的常见引用。它使阅读代码更容易知道哪些变量是 jQuery 包装的。
//Item has been "cached" for later use in the script as a jQuery object.
var $item = $(this);
回答by locrizak
For me a common practice is this:
对我来说,一个常见的做法是:
If a variable is private I use an underscore like this:
如果一个变量是私有的,我使用这样的下划线:
(function(){
var _foo = "bar";
})()
If it's public I'll use no underscore:
如果它是公开的,我将不使用下划线:
var foo = "bar"
And if it's a jQuery selector I'll use the $
:
如果它是一个 jQuery 选择器,我将使用$
:
var $foo = $('bar');
//then you can access it like this
$foo.attr('id')
It's just coding convention and it allows you to quickly reference what type the variable is later in the code.
这只是编码约定,它允许您在代码的后面快速引用变量的类型。
回答by sanmai
Many people using jQuery will prefix variables that contain a jQuery object with a $, so that they are easily identified. Consider this example:
许多使用 jQuery 的人会在包含 jQuery 对象的变量前加上 $,以便于识别。考虑这个例子:
var $img = $(".someclass span.otherclass img");
/* somewhere later in the code */
$img.bind("click", function() {/*...*/});
回答by supajb
In my experience this is just a readability. Some developers like to prefix their variables so that they are easy to spot. It could also be a PHP habit creeping it's way in to Javascript.
根据我的经验,这只是一种可读性。一些开发人员喜欢给他们的变量加上前缀,以便他们很容易被发现。它也可能是一种 PHP 习惯逐渐渗透到 Javascript 中。
回答by Marino ?imi?
Dollar signs in code that uses JQuery commonly means that the variable in question is a jQuery variable (an object wrapped by jquery).
使用 JQuery 的代码中的美元符号通常意味着所讨论的变量是 jQuery 变量(由 jquery 包装的对象)。