Its a general question about something i seem to encounter a lot:
When should i use
function Bla(){return function(){alert("bla");}}
and call the main function Bla,
and when should I use
function Bla(){function innerBla(){alert("bla");}}
and call Bla.innerBla?
What is the difference between them?
Those are two different ways of doing things, and they operate differently.
The first one is a function that returns another function. Thus, to invoke the inner function, you need to first call the outer one,
Bla, (which returns the inner one) and then invoke the returned value (the inner function):The second one just defines an inner function, and there’s no way of invoking that inner function from outside of the outer function because it’s scoped only within the outer function
Bla:Bla.innerBlaisundefinedbecause the object (functions are objects in JavaScript)Bladoes not have a member calledinnerBlaattached to it.If you want to invoke it like
bla.innerBla, you should do something like this:Or you can have something like this (a pattern that I frequently use):
If you want to use the constructor pattern (
new), you need to do something like this:This is equivalent to having a public property on an instance of an object in an OO language.
And finally, if you want to expose
innerBlaby every ‘instance’ (achieved using a constructor i.e. invokingblausing thenewkeyword) ofbla, you should add the function tobar.prototype.innerBla:This is similar to having a static method.
On a side note, avoid naming functions with an initial capital case letter (pascal-case) because by convention, usually we only capitalize functions which need to be invoked using the
newkeyword (constructors).