2

In CoffeeScript with jQuery, is there any difference for following statements?

jQuery ($) ->
jQuery ->
$ - >

3 Answers 3

4

The first one is different from the other two, just as in plain JavaScript. There, you use the global name "jQuery" to register an event handler for the "DOM ready" event while making sure that the shortcut $ is linked to jQuery. The other two styles don't do that - therefore, in the local scope of the event handler, $ will be of whatever value it is outside.

Sign up to request clarification or add additional context in comments.

Comments

1

It's important to know that $(handler) is the same as $(document).ready(handler) All three of the statements in your question are basically setting a handler for the jQuery.ready function.

With that out of the way, jQuery will pass a variable to the handler provided to the ready function which is the jQuery object. So in your first example you're handler is just taking advantage of this and (re)setting $ to be the same as jQuery. It's not required for your handler to accept the variable that jQuery is passing which is why it's okay for your two other handlers not to accept any arguments.

You generally only need to do this when there is another library that uses the $ globally such as jQuery.

Comments

1

By default, jQuery creates a global object named jQuery and a global alias named $. That is, window.$ = window.jQuery. That's why you may see different documentation referencing both. Certain other libraries are also fond of using $ as their name. That's why jQuery offers noConflict mode, which lets you reset $ to whatever its previous value was.

So to give you a short answer: You should prefer $ -> unless you're using noConflict.

Here, for reference, are the official docs on the jQuery function when it's given a function as an argument: http://api.jquery.com/jQuery/#jQuery3

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.