J
JohnS
Hi,
A lot of functions (classes) in my JavaScript app are singletons. So, I have
been exploring ways making JavaScript functions singletons. I thought I'ld
run one idea past you all and get some feed back.
The usual method of making singletons is to have a static member that
returns one instance of the class. But, JavaScript has no notion of static.
The closest it has is prototype functions.
// The singleton class
function Single() {
// call the "static" GetInstance()
return Single.prototype.GetInstance();
}
// The only instance.
Single.prototype._single = null;
// static function
Single.prototype.GetInstance = function() {
if( !Single.prototype._single ) {
Single.prototype._single = this;
}
return Single.prototype._single;
}
----------
So, "new Single() == new Single()" is true.
Or "new Single() == Single.prototype.GetInstance()"
What do you all think? Is the "new Single()" going to be confusing? Is there
are way to do "Single.GetInstance()"? I think the prototype version is
unweildy.
-------------------------------------------------------------
When can I refer to prototype functions or prototypes full stop? It appears
that "this.GetInstance" exists in "new Single()", but I can't call it.
JohnS
A lot of functions (classes) in my JavaScript app are singletons. So, I have
been exploring ways making JavaScript functions singletons. I thought I'ld
run one idea past you all and get some feed back.
The usual method of making singletons is to have a static member that
returns one instance of the class. But, JavaScript has no notion of static.
The closest it has is prototype functions.
// The singleton class
function Single() {
// call the "static" GetInstance()
return Single.prototype.GetInstance();
}
// The only instance.
Single.prototype._single = null;
// static function
Single.prototype.GetInstance = function() {
if( !Single.prototype._single ) {
Single.prototype._single = this;
}
return Single.prototype._single;
}
----------
So, "new Single() == new Single()" is true.
Or "new Single() == Single.prototype.GetInstance()"
What do you all think? Is the "new Single()" going to be confusing? Is there
are way to do "Single.GetInstance()"? I think the prototype version is
unweildy.
-------------------------------------------------------------
When can I refer to prototype functions or prototypes full stop? It appears
that "this.GetInstance" exists in "new Single()", but I can't call it.
JohnS