SitePoint Sponsor

User Tag List

Results 1 to 2 of 2

Thread: n00b question

  1. #1
    SitePoint Member
    Join Date
    Oct 2011
    Posts
    1
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    n00b question

    Hi. I need to know how to call a function within a function.

    Code JavaScript:
    function parent() {
    function child() {
    //code here
    }
    }
     
    //how do i call child from outside of parent?

  2. #2
    SitePoint Addict sdleihssirhc's Avatar
    Join Date
    Feb 2009
    Posts
    387
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    In your example, there is no way to call the child function. It's something you could do in JavaScript to emulate the private variables of other languages.

    If you want it to be publicly accessible, you could do something like this:

    Code JavaScript:
    function parent() {
        function child() {
            // code here
        }
        parent.child = child;
    }

    ...But it's important to remember that the "child" function is not created until the "parent" function is called.

    Code JavaScript:
    function parent() {
        function child() {
            // code here
        }
        parent.child = child;
    }
     
    parent.child(); // throws an error
     
    parent(); // "child" function is created and assigned to parent.child
    parent.child(); // works!
     
    parent(); // "child" function is rebuilt and reassigned
    parent(); // "child" function is rebuilt and reassigned
    parent(); // "child" function is rebuilt and reassigned
    parent(); // "child" function is rebuilt and reassigned
    Last edited by sdleihssirhc; Oct 31, 2011 at 12:12. Reason: expanded on answer
    I'm the web overlord for Graphic Business Systems


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
  •