javascriptoopprivate-membersjavascript-namespaces

OOP, private functions inside a top level method of the namespace


I have a js script which declares a namespace, then has a method called run() which I can call from inside a XUL script like myNamespace.run():

var myNamespace = {
    run: function() {
        var selectedText = getSelText();
        alert (selectedText);

        var getSelText = function() {
            var focusedWindow = document.commandDispatcher.focusedWindow;
            var selText = focusedWindow.getSelection();

            return selText.toString();
        }
    }
}

I want to be able to call getSelText() inside myNamespace.run() without needing to declare getSelText() as another top level function of myNamespace. Instead, it should be like a private method inside myNamespace.run().

When I run this script I receive an error:

getSelText is not a function.

I'm pretty new to JavaScript, so I don't know the best way of designing this. Is it possible to acheive what I am trying? Am I going about this the wrong way?

Appreciate any help!


Solution

  • If you declare getSelText as a var, it needs to come before any statements where you use it. Just make the var getSelText = ... statement the first statement in the run function.


    Supplemental information:

    var statements in Javascript are "hoisted" to top of the function they're declared in, so this:

    function() {
        var a = 42;
        // Other stuff...
        var b = 23; 
    }
    

    really means this:

    function() {
        var a = 42, b;
        // Other stuff...
        b = 23;
    }
    

    Another similar construct in Javascript is the function statement, as opposed to function expressions:

    function() {
        var fn1 = function() { return fn2(); }; // Function expression
        alert(fn1());
    
        // Function statement
        function fn2() {
            return "Hello from fn2";
        }
    }
    

    If you ran the code above, it would successfully alert "Hello from fn2". This is because function statements are hoisted to the tip-top before any other statement within the scope they're declared in. As you can see, this could get very confusing. Probably the best convention to follow is to use function expressions and declare them in the order that you need.