Categories:
Partners
Web Hosting
We've partnered with HostGator for reliable, affordable hosting starting at $3.95/mon. Use coupon code "javascriptkit25" for 25% off any package.

Exposing inner functions to the outer world

Okay, suppose we have this arrangement:

function Ftimes() { 
    function Ftimes3(x) { 
        return x * 3 
        } 
    function Ftimes4(x) 
        return x * 4 
        } 
    } 

How can we allow people to access these inner functions directly?  It's actually easier than you might think -- just return a new Object() with these functions as methods of the object.

function Ftimes() { 
    var FtimesObj = new Object() 
    function Ftimes3(x) { 
        return x * 3 
        } 
    function Ftimes4(x) 
        return x * 4 
        } 
    FtimesObj.Ftimes3 = Ftimes3 
    FtimesObj.Ftimes4 = Ftimes4 
    return FtimesObj 
    } 
Multi = new Ftimes()

Now, the Multi object has two methods: Multi.Ftimes3(x) and Multi.FTimes4(x).  This is how JavaScript's Math object is defined -- as a collection of methods and properties.  Check it out, as we ask the above code what Multi.Ftimes3(5) is:

function Ftimes() { 
    var FtimesObj = new Object() 
    function Ftimes3(x) { 
        return x * 3 
        } 
    function Ftimes4(x) { 
        return x * 4 
        } 
    FtimesObj.Ftimes3 = Ftimes3 
    FtimesObj.Ftimes4 = Ftimes4 
    return FtimesObj 
    } 

Multi = new Ftimes() 
alert(Multi.Ftimes3(5)) // alerts 15

By using unique object names, and placing as many functions within a container function as possible, we greatly reduce the number of object names which other JavaScripters cannot use, while losing no functionality in our objects.  So potential conflicts between multiple JavaScripts are reduced significantly.

Copyright 1997-2014 JavaScript Kit. NO PART may be reproduced without author's permission.