Search code examples
javascriptapiprivate-members

Javascript API private functions and modules


This is a question about scope in javascript and making APIs, I have the following code:

function test_objectExplorer()
{
    var obj = {
        a:true,
        b:12,
        c:{
            a:12,
            b:null
        },
        d:function(msg){
            alert(msg);
        }
    };
    alert(objectExplorer(obj));
}


function objectExplorer(obj)
{

var explore = function(obj,depthCount)
{
    var str = "";
    for(var prop in obj)
    {
        for(i=0; i<depthCount; i++)str += "    ";
        str += prop + " = " + obj[prop] + "\n";
        if( (typeof obj[prop] == 'string') || obj[prop] instanceof String)continue;
        str += explore(obj[prop],depthCount+1);
    }
    return str;
}
return explore(obj,0);
}

I use the objectExplorer function for 'looking' at javascript objects. It is the internal explore function which actually does the work, as you see, but I used the 2nd argument as a depth counter to provide appropriate text indentation for the output string.

I didn't want users to have to use a function which required an additional argument which always has to be supplied in the first instance as the number zero, so I wrapped it in the 'API' function call objectExplorer. My question is, is this the right approach to take? I come from C#, Java and other class-based OOP languages and the API in those are just the public properties and methods but in javascript I know of no way to make things private other than hiding their declaration inside another object.


Solution

  • In JavaScript the function determines the scope of variables. So

    function() {
      for (var i=0 ; i<10;i++) {
        var a = i; 
      }
      alert(a);
    }
    

    will alert 9, because the variable is within the same function.

    If you want to make modules maybe this will help you out: http://blog.davidpadbury.com/2011/08/21/javascript-modules/