SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Enthusiast
    Join Date
    Apr 2005
    Posts
    41
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    var = function {} construct

    Hello guys and gals,
    I am excited to start using available javascript libraries, like Prototype and jQuery and when I look at their code, i see that they use a lot of
    Code JavaScript:
    var = function {}
    What is it? A function assigned to variable? Why is it good? Why should you use it?

    Thanks for help!

  2. #2
    SitePoint Evangelist bals28mjk's Avatar
    Join Date
    Aug 2007
    Posts
    405
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    It's a function reference assigned to a variable assuming that you assign a variable to the var statement. It's good in situations where a function reference is called for e.g setTimeout method. Also, it's good for a quick way of creating your methods for custom objects, plus it limits the names used in your global scope.

  3. #3
    CSS & JS/DOM Adept bronze trophy
    Join Date
    Mar 2005
    Location
    USA
    Posts
    5,482
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Code:
    var funcName = function(){}
    is just another way to write
    Code:
    function funcName(){}
    The first is more flexible than the second. It allows you to assign a function to a variable or property just like a string, number, or other kind of object.

    The second only allows you to create the function within the current context, while the first allows you to do something like this:
    Code:
    myObj.funcName = function(){}
    The following is not valid:
    Code:
    function myObj.funcName(){}
    We miss you, Dan Schulz.
    Learn CSS. | X/HTML Validator | CSS validator
    Dynamic Site Solutions
    Code for Firefox, Chrome, Safari, & Opera, then add fixes for IE, not vice versa.

  4. #4
    SitePoint Enthusiast
    Join Date
    Apr 2005
    Posts
    41
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    it's good for a quick way of creating your methods for custom objects
    Thanks for explanations and examples, guys. Now i get it.


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
  •