OOP, private functions inside a top-level namespace method

I have a js script that declares a namespace and then has a run() method that I can call from within the 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 requiring the declaration of getSelText() as another top-level function myNamespace . Instead, it should be as a private method inside myNamespace.run() .

When I run this script, I get an error message:

getSelText not a function.

I am new to JavaScript, so I don’t know what is the best way to develop this. Is it possible to achieve what I'm trying to do? Am I going about it wrong?

Appreciate any help!

+4
source share
2 answers

If you declare getSelText as var , it should appear before any statements in which you use it. Just make the var getSelText = ... statement the first statement in the run function.


Additional Information:

Operators

var in Javascript "rises" to the top of the function in which they are declared, so this is:

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

really means the following:

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

Another similar construct in Javascript is a 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 run the code above, it will successfully warn "Hello from fn2". This is because function statements rise to the top to any other operator within the scope in which they are declared. As you can see, this can become very confusing. Probably the best deal is to use function expressions and declare them in the order you need.

+4
source

It is called a module template. Create an anonymous function (to determine the scope) that is immediately called and returns an open interface.

 var myNamespace = (function() { // private functions for your namespace var getSelText = function() { ... }; return { run: function() { var selectedText = getSelText(); alert (selectedText); } }; })() 
+7
source

Source: https://habr.com/ru/post/1403245/


All Articles