Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 885
bobbyrne01 Avatar asked Dec 21 '22 00:12

bobbyrne01


1 Answers

It's called the module pattern. Create an anonymous function (for scoping) that gets called immediately and return the public interface.

var myNamespace = (function() {
  // private functions for your namespace
  var getSelText = function() {
        ...
  };

  return {
    run: function() {
        var selectedText = getSelText();
        alert (selectedText);
    }
  };
})()
like image 123
Jason Harwig Avatar answered May 18 '23 20:05

Jason Harwig