开发者

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

In JQuery and other libraries I keep seeing a dollar sign $ befo开发者_StackOverflowre 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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜