What is the $ symbol used for in JavaScript

前端 未结 3 2001
眼角桃花
眼角桃花 2020-12-04 20:57

I am a JavaScript learner and have been researching this matter, but with no success. What is the $ symbol used for in JavaScript besides regular expressions?

3条回答
  •  半阙折子戏
    2020-12-04 21:38

    I became acquainted with it in JavaScript when I started using the Prototype framework. In Prototype, $ is simply the name of an often used function (very, very much simplified - a short for document.getElementById). Personally, I like the terseness of it.

    Afaik, it's not used for anything by the language itself.

    For what it's worth, Douglas Crockford advises against using $ in the variable/function names you write:

    Do not use $ (dollar sign) or \ (backslash) in names.


    Adding another, rather opinionated, quote from Mr. Crockford's talk "And Then There Was JavaScript":

    Dollar sign was added to the language specifically for use by code generators and macro processes, so if you have machines writing code then the machines need to be confident that the variables that they create will not conflict with variables that the humans are going to create. To distinguish them, we’ll allow the machines to use dollar sign. Some of the ninjas found out about that and thought oh, dollar sign, I can use dollar sign as a function name, so they’re out there doing that. And it looks stupid. I mean, look at a program with dollar sign.

提交回复
热议问题