可能的复制品: 为什么 javascript 变量以美元符号开始
我看到人们在使用 jQuery 时在变量前使用美元符号。这背后有什么原因吗?我错过了一些基本的东西,还是这只是一个常见的做法?
它是对 jQuery 包装对象的常见引用。它使得阅读代码更容易知道哪些变量是 jQuery 包装的。
//Item has been "cached" for later use in the script as a jQuery object. var $item = $(this);
根据我的经验,这只是一种可读性。一些开发人员喜欢给他们的变量加上前缀,这样他们就很容易被发现。这也可能是 PHP 的一种习惯,正在慢慢地渗透到 Javascript 中。
许多使用 jQuery 的人会在包含 jQuery 对象的变量前面加上 $,这样就很容易识别它们。考虑一下这个例子:
var $img = $(".someclass span.otherclass img"); /* somewhere later in the code */ $img.bind("click", function() {/*...*/});
使用 JQuery 的代码中的美元符号通常意味着所讨论的变量是一个 jQuery 变量(由 JQuery 包装的对象)。
对我来说,一个常见的做法是:
如果一个变量是私有的,我使用下划线如下:
(function(){ var _foo = "bar"; })()
如果它是公共的,我将不使用下划线:
var foo = "bar"
And if it's a jQuery selector I'll use the $:
$
var $foo = $('bar'); //then you can access it like this $foo.attr('id')
这只是编码约定,它允许您在代码中快速引用变量的类型。