简体   繁体   中英

Why do I see a dollar sign before some constructors in JavaScript?

In JQuery and other libraries I keep seeing a dollar sign $ before constructors.

What is the significance of that symbol?

One website told me this:

Rather than having to type out jQuery each time, we use an alias, a simple dollar sign (the shortest legal identifier that's not alphanumeric).

$ is a valid variable/function identifier in Javascript. It is used in frameworks such as jQuery.

In JavaScript identifier can start with _ OR $ or Character. And $ is valid to be used in identifiers. In the JavaScript frameworks(like JQuery) $ is very nicely used. However its always suggested as good practice not to user the $ for identifiers.

The $ sign does not have any special meaning in JavaScript, unlike languages like Perl or PHP, where it's used to indicate that something is a variable. So when you see something like var $foo it's is only a variable whose name happens to start with dollar.

You see a lots of dollars out there because many popular JavaScript libraries have chosen a single $ as a name for their main object. It's short and handy to have a function you can call with $() . As a consequence of this, some programmers use a naming convention for their own variables: they use $ as a prefix if the variable is an instance of the framework object. That makes it easy to spot visually if a variable is an scalar or an object.

An example in jQuery:

var txt = "This a regular text";
var links = document.getElementsByTagName("a"); // Array of DOM nodes
var $links = $("a"); // jQuery object

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM