What is the meaning of “$” sign in JavaScript

后端 未结 7 2175
无人共我
无人共我 2020-11-22 10:54

In the following JavaScript code there is a dollar ($) sign. What does it mean?

$(window).bind(\'load\', function() {
    $(\'img.protect\').pro         


        
7条回答
  •  隐瞒了意图╮
    2020-11-22 11:57

    From another answer:

    A little history

    Remember, there is nothing inherently special about $. It is a variable name just like any other. In earlier days, people used to write code using document.getElementById. Because JavaScript is case-sensitive, it was normal to make a mistake while writing document.getElementById. Should I capital 'b' of 'by'? Should I capital 'i' of Id? You get the drift. Because functions are first-class citizens in JavaScript, you can always do this:

    var $ = document.getElementById; //freedom from document.getElementById!
    

    When Prototype library arrived, they named their function, which gets the DOM elements, as '$'. Almost all the JavaScript libraries copied this idea. Prototype also introduced a $$ function to select elements using CSS selector.

    jQuery also adapted $ function but expanded to make it accept all kinds of 'selectors' to get the elements you want. Now, if you are already using Prototype in your project and wanted to include jQuery, you will be in problem as '$' could either refer to Prototype's implementation OR jQuery's implementation. That's why jQuery has the option of noConflict so that you can include jQuery in your project which uses Prototype and slowly migrate your code. I think this was a brilliant move on John's part! :)

提交回复
热议问题