SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Enthusiast
    Join Date
    Nov 2009
    Location
    USA
    Posts
    60
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    JQuery Functions Declarations

    What is the difference between:
    Code:
    function removeLightbox() {...}
    AND

    Code:
    removeLightbox = function(){...}

  2. #2
    Forums Designer
    Join Date
    Jun 2004
    Posts
    422
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Second one is more flexible, allowing you to declare function depending on conditions, like:

    Code:
    if(whatever)
    {
     var removeLightbox = function() { return 'f1'; };
    }
    else
    {
     var removeLightbox = function() { return 'f2'; };
    }
    then second one can be used inside objects, like $.removeLightbox = function() {}; which can't be done with first method.

    With second method you can't use function before its declaration, but with first method you can.

    That's all I can think of. I'm sure there are many other differences.

  3. #3
    SitePoint Enthusiast
    Join Date
    Nov 2009
    Location
    USA
    Posts
    60
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks, that helps for now

  4. #4
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,705
    Mentioned
    102 Post(s)
    Tagged
    4 Thread(s)
    Quote Originally Posted by mpiantella View Post
    What is the difference between:
    Code:
    function removeLightbox() {...}
    AND

    Code:
    removeLightbox = function(){...}
    The first one declares a function using the function statement. The second declares a function using a function operator.

    The main difference between them is that functions created using the function operator do not exist until execution reaches that code. Function statements are hoisted to the top of their context. That means that a function statement can be made at the bottom of the code, but it can still be used from places above the function statement.

    So while the function statement has hoisting as its advantage, it's a hidden advantage that most people aren't explicitly aware of, even though they implicitly make use of it.

    The function operator allows you to create functions just when they're needed.
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript


Tags for this Thread

Bookmarks

Posting Permissions

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