Re: Singleton
On May 24, 8:58 am, Ugo <priv...@nospam .itwrote:
I doubt that is what Richard meant by "what it is you are trying to
do". You are more likely trying to "implement a tabbed pane widget" or
"send user data to the server". Unless this is just an academic
exercise.
>
all this things :P
>
>
>
But, in this way I can not to declare "private" variables/methods in an
elegant way:
>
I don't like it:
>
var singleton;
>
(function()
{
// "privare" prop
var a = 1;
// "private" method
function b( )
{
alert('hi');
}
>
// Obj
singleton = {
hi : b,
a: a
};
>
})();
Why don't you "like it"? Because it does not involve a constructor
function? Because it is not like Java? These seem like unfortunates
reason to avoid the simplest most direct technique to achieve your
goal. What you have written above is one normal way to write a
JavaScript singleton and is far simpler than your previous code
examples.
I am not always so concerned with this sort of closure "privacy" and
would just write
var singleton = {
_a: 1,
hi: function() {alert('hi');}
};
Some folks argue against the underscore privacy convention but I think
they are fooling themselves that things can be protected in
JavaScript. Someone could come along and reassign to the singleton
variable and destroy everything anyway.
Peter
On May 24, 8:58 am, Ugo <priv...@nospam .itwrote:
>The best way of doing something depends at least in part on what it is
>you are trying to do.
A generic way to create a singleton object
>you are trying to do.
A generic way to create a singleton object
do". You are more likely trying to "implement a tabbed pane widget" or
"send user data to the server". Unless this is just an academic
exercise.
all this things :P
>
A generic way to create a singleton object with global access is to
use a object literal.
use a object literal.
var someSingleton = {
someProperty: function() {},
someOtherProper ty: 55
};
someProperty: function() {},
someOtherProper ty: 55
};
But, in this way I can not to declare "private" variables/methods in an
elegant way:
>
I don't like it:
>
var singleton;
>
(function()
{
// "privare" prop
var a = 1;
// "private" method
function b( )
{
alert('hi');
}
>
// Obj
singleton = {
hi : b,
a: a
};
>
})();
function? Because it is not like Java? These seem like unfortunates
reason to avoid the simplest most direct technique to achieve your
goal. What you have written above is one normal way to write a
JavaScript singleton and is far simpler than your previous code
examples.
I am not always so concerned with this sort of closure "privacy" and
would just write
var singleton = {
_a: 1,
hi: function() {alert('hi');}
};
Some folks argue against the underscore privacy convention but I think
they are fooling themselves that things can be protected in
JavaScript. Someone could come along and reassign to the singleton
variable and destroy everything anyway.
Peter
Comment