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:
getSelTextis 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!
If you declare
getSelTextas avar, it needs to come before any statements where you use it. Just make thevar getSelText = ...statement the first statement in therunfunction.Supplemental information:
varstatements in Javascript are “hoisted” to top of the function they’re declared in, so this:really means this:
Another similar construct in Javascript is the function statement, as opposed to function expressions:
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.