Ugo wrote:
how do you make a singleton access class?
How do you define a "singleton access class"?
Do you know a better way of this one:
The best way of doing something depends at least in part on what it is
you are trying to do.
var singletonClass = (function( )
{
// Private variable
var instance = null;
There is little point in assigning null to this variable as its default
undefined value will be just as false as the null value when you test it
with - !instance -.
// Private Constructor
function myClass( )
{
//...
}
return new function( )
I can think of no circumstances under which it makes sense to use the -
new - operator with a function expression as its operand. In this case
it would be simpler (and more efficient) to have an object literal
returned at this point. That object could easily define - constructor -
and - getInstance - properties.
{
this.constructo r = null;
this.getInstanc e = function( )
{
if( ! instance )
{
instance = new myClass( );
instance.constr uctor = null;
As you are using a constructor to create this object instance it would
be possible to define the created object's - constructor property on the
prototype of the constructor. Though there may be no good reason for
using a contractor to create the object at all as you are only going to
be creating one instance of the object, and so again a literal could be
used instead.
}
return instance;
}
}
})( );
The result of those changes could look like:-
var singletonClass = (function( ){
// Private variable
var instance;
return ({
constructor:nul l,
getInstance:fun ction( ){
return (
instance||
(
instance = {
constructor:nul l
}
)
);
}
});
})();
- though that is almost certainly less than would be needed in any real
context, but you will always suffer that if you don't define what it is
exactly that you are trying to achieve.
Richard.