Your code can also be written as:
var One = {
ABC:{
SayHello: function() {
alert('hello');
}
}
};
One.ABC.SayHello(); //=> hello
This variable definition creates a (pseudo) namespace One
(actually, an Object in the global namespace). The first property of One
is ABC
. ABC
is an Object too and has one property, the public methodSayHello
.
If you wanted SayHello
to be private, this could be a way to do it:
var Two = {
ABC: ( function(){
// SayHello is a private function within this
// anonymous function
// it can only be accessed by a public method
// you create (here it's the method Hi)
function SayHello() {
alert('hello from Two.ABC');
}
return {
SayHello: function(){alert('you are not allowed to say Hello!');},
Hi: SayHello
};
} )()
}
Two.ABC.SayHello(); //=> you are not allowed to say Hello!
Two.ABC.Hi(); //=> hello from Two.ABC
Now Two.ABC
is an object too, but it is created using an anonymous constructor function instantiated on creation (a singleton pattern I think it's called). Within that constructor SayHello
is now a private (not publicly accessible) function. You'll have to assign some public method to access SayHello
(here: Two.ABC.Hi
), otherwise it will be completely hidden. In this example, because SayHello
is defined within the anonymous function scope, it is accessible for the methods that anonymous function returns, which in turn are accessible to the parent scopes (ABC and TWo). In other words, the function SayHello
is enclosed by the methods the singleton returns.