有问题的代码在这里:

var $item = $(this).parent().parent().find('input');

在变量名中使用美元符号的目的是什么,为什么不直接排除它呢?


当前回答

美元符号就像一个普通的字母或下划线(_)。它对解释器没有特别的意义。

与许多类似的语言不同,Javascript中的标识符(如函数名和变量名)不仅可以包含字母、数字和下划线,还可以包含美元符号。它们甚至可以以美元符号开头,或者只由美元符号组成,没有其他符号。

因此,$在Javascript中是一个有效的函数或变量名。

为什么要在标识符中使用美元符号?

该语法并没有真正强制在标识符中使用美元符号的任何特定用法,因此取决于您希望如何使用它。在过去,通常建议只在生成的代码中以美元符号开始标识符——也就是说,不是手工而是由代码生成器创建的代码。

然而,在你的例子中,情况似乎并非如此。看起来好像有人只是为了好玩才在开头放了一个美元符号——也许他们是PHP程序员,出于习惯才这么做的,或者别的什么。在PHP中,所有变量名前面都必须有一个美元符号。

There is another common meaning for a dollar sign in an interpreter nowadays: the jQuery object, whose name only consists of a single dollar sign ($). This is a convention borrowed from earlier Javascript frameworks like Prototype, and if jQuery is used with other such frameworks, there will be a name clash because they will both use the name $ (jQuery can be configured to use a different name for its global object). There is nothing special in Javascript that allows jQuery to use the single dollar sign as its object name; as mentioned above, it's simply just another valid identifier name.

其他回答

美元符号就像一个普通的字母或下划线(_)。它对解释器没有特别的意义。

与许多类似的语言不同,Javascript中的标识符(如函数名和变量名)不仅可以包含字母、数字和下划线,还可以包含美元符号。它们甚至可以以美元符号开头,或者只由美元符号组成,没有其他符号。

因此,$在Javascript中是一个有效的函数或变量名。

为什么要在标识符中使用美元符号?

该语法并没有真正强制在标识符中使用美元符号的任何特定用法,因此取决于您希望如何使用它。在过去,通常建议只在生成的代码中以美元符号开始标识符——也就是说,不是手工而是由代码生成器创建的代码。

然而,在你的例子中,情况似乎并非如此。看起来好像有人只是为了好玩才在开头放了一个美元符号——也许他们是PHP程序员,出于习惯才这么做的,或者别的什么。在PHP中,所有变量名前面都必须有一个美元符号。

There is another common meaning for a dollar sign in an interpreter nowadays: the jQuery object, whose name only consists of a single dollar sign ($). This is a convention borrowed from earlier Javascript frameworks like Prototype, and if jQuery is used with other such frameworks, there will be a name clash because they will both use the name $ (jQuery can be configured to use a different name for its global object). There is nothing special in Javascript that allows jQuery to use the single dollar sign as its object name; as mentioned above, it's simply just another valid identifier name.

在使用jQuery时,使用$符号作为变量名的前缀只是一种惯例;它是完全可选的,仅用于指示变量保存jQuery对象,如示例中所示。

这意味着当需要在对象上调用另一个jQuery函数时,您不需要再次将它包装在$()中。例如,比较这些:

// the usual way
var item = $(this).parent().parent().find('input');
$(item).hide(); // this is a double wrap, but required for code readability
item.hide(); // this works but is very unclear how a jQuery function is getting called on this 

// with $ prefix
var $item = $(this).parent().parent().find('input');
$item.hide(); // direct call is clear
$($item).hide(); // this works too, but isn't necessary

使用$前缀,已经包含jQuery对象的变量可以立即识别,代码更易于阅读,并消除了使用$()的双/多次换行。

没有理由。也许编写代码的人来自PHP。它的效果与将其命名为“_item”或“item”或“item$$”相同。

作为一个后缀(如“item$”,发音为“items”),它可以表示一个可观察对象,如DOM元素,作为一种称为“芬兰符号”的约定,类似于匈牙利符号。

我可能会补充说,使用它的jQuery可以让你做这样的事情,例如:

$.isArray(myArray);

在你的例子中,$除了作为名称的一个字符外没有任何特殊的意义。

然而,在ECMAScript 6 (ES6)中,$可以表示模板文字

var user = 'Bob'
console.log(`We love ${user}.`); //Note backticks
// We love Bob.