Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    New Coder
    Join Date
    Jun 2009
    Posts
    31
    Thanks
    7
    Thanked 1 Time in 1 Post

    code explanation

    Hi

    I was going through jquery enlightenment book and came across following code which is used to avoid conflict with other libraries


    (function($){
    // Use $ alias worry-free of conflicts

    })(jQuery)


    Could somebody please explain what is happening here?

    Thanks

  • #2
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,620
    Thanks
    0
    Thanked 645 Times in 635 Posts
    (function() {})() is a self executing anonymous function

    (jQuery) is the parameter being passed into the function

    ($) is the same parameter inside the function

    To properly use it without conflicts you'd also need to define jQuery.noConflict(); outside of the function so theat the $ is not defined as an alias for jQuery and can be used for something else outside of that particular function.

    See http://javascriptexample.net/jquery01.php for a further explanation
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

  • Users who have thanked felgall for this post:

    skywaves (02-11-2014)

  • #3
    New Coder
    Join Date
    Jun 2009
    Posts
    31
    Thanks
    7
    Thanked 1 Time in 1 Post
    Thanks
    I think I need to read more about self executing anonymous function

    A bit confusing at first.

    EDIT:
    After going through the link now I know that jQuery variable is named as $. It could have been named anything.

    Closures and immediately-invoked-function-expression-iife also helped.

    I have also bookmarked javascript by example

    Thanks again
    Last edited by skywaves; 02-11-2014 at 11:11 PM. Reason: Info


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •