Singleton

U

Ugo

Hi guys,

how do you make a singleton access class?

Do you know a better way of this one:

var singletonClass = (function( )
{
// Private variable
var instance = null;

// Private Constructor
function myClass( )
{
//...
}

return new function( )
{
this.constructor = null;

this.getInstance = function( )
{
if( ! instance )
{
instance = new myClass( );
instance.constructor = null;
}

return instance;
}
}
})( );
 
S

Sam --

Hi guys,

how do you make a singleton access class?

Do you know a better way of this one:

var singletonClass = (function( )
{
// Private variable
var instance = null;

// Private Constructor
function myClass( )
{
//...
}

return new function( )
{
this.constructor = null;

this.getInstance = function( )
{
if( ! instance )
{
instance = new myClass( );
instance.constructor = null;
}

return instance;
}
}
})( );
Pure qui? :))
se ti vede ZERO...


ciao
 
R

RoLo

Do you know a better way of this one:
Yes

change this:
   return new function( )

to this:
return function( )

;-)
 
R

RoLo

Yes

change this:
    return new function( )

to this:
    return function( )

;-)

ok... sorry, I over read you code.. you can ignore my previous comment.
 
R

Richard Cornford

Ugo said:
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.constructor = null;

this.getInstance = function( )
{
if( ! instance )
{
instance = new myClass( );
instance.constructor = 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:null,
getInstance:function( ){
return (
instance||
(
instance = {
constructor:null
}
)
);
}
});
})();

- 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.
 
P

Peter Michaux

Hi guys,

how do you make a singleton access class?

Do you know a better way of this one:

var singletonClass = (function( )
{
// Private variable
var instance = null;

// Private Constructor
function myClass( )
{
//...
}

return new function( )
{
this.constructor = null;

this.getInstance = function( )
{
if( ! instance )
{
instance = new myClass( );
instance.constructor = null;
}

return instance;
}
}

})( );

This does not look like something a JavaScript programmer would write.
In JavaScript, assigning an object literal to a global variable would
likely achieve the purpose of a Singleton pattern in Java, for
example, for many situations. What is your real application?

Peter
 
U

Ugo

how do you make a singleton access class?
How do you define a "singleton access class"?

i wanted a function/object which restricts the instantiation of one my
object one time and which it ables one global access
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 (and if it's possible I'd like
to adopt the GoF's "roles" - applyed to JS)
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 -.

IMHO, (new myClass()) can not be null|false|undefined..
so that initialization was good
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.

ahh, in effect :p
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.
Mmm


The result of those changes could look like:-

let's look at
var singletonClass = (function( ){
// Private variable
var instance;
return ({
constructor:null,
getInstance:function( ){
return (
instance||
(
instance = {
constructor:null
}
)
);
}
});
})();

Ok, it's no much different of mine, you have converted my code with object
literal
- 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.

see before

THKS
 
P

Peter Michaux

i wanted a function/object which restricts the instantiation of one my
object one time and which it ables one global access



A generic way to create a singleton object


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.

A generic way to create a singleton object with global access is to
use a object literal.

var someSingleton = {
someProperty: function() {},
someOtherProperty: 55
};

Peter
 
T

Thomas 'PointedEars' Lahn

Ugo said:
IMHO, (new myClass()) can not be null|false|undefined..

Yes, it can ;-)

function myClass()
{
this.toString = function() {
var a = [null, false, a];
return a[Math.floor(Math.random() * a.length)];
};
}

window.alert(new myClass());


PointedEars
 
P

P. Prikryl

Yes, it can ;-)
You are just plain wrong.
function myClass()
{
this.toString = function() {
var a = [null, false, a];
return a[Math.floor(Math.random() * a.length)];
};
}

window.alert(new myClass());
Irrelevant code - what does it prove?
 
P

Peter Michaux

Ugo said:
IMHO, (new myClass()) can not be null|false|undefined..

Yes, it can ;-)

function myClass()
{
this.toString = function() {
var a = [null, false, a];
return a[Math.floor(Math.random() * a.length)];
};
}

window.alert(new myClass());

That is "null"|"false"|"undefined"

Try this

function myClass() {
this.toString = function() {
var a = [null, false, a];
return a[Math.floor(Math.random() * a.length)];
};
}

var inst = (new myClass());
if (inst === null ||
inst === false ||
inst === undefined) {
alert('Thomas is right');
}
else {
alert('Thomas is wrong');
}

This is, of course, the expected behavior according to ECMAScript
spec. Please see section 13.2.2.

Peter

P.S. I do appreciate the humor. I was just playing Thomas.

Footnotes:
"P.S." is abbreviation for "post scriptum", a Latin expression meaning
"after writing"
 
T

Thomas 'PointedEars' Lahn

P. Prikryl said:
You are just plain wrong.

Or I could have made a joke.
function myClass()
{
this.toString = function() {
var a = [null, false, a];
return a[Math.floor(Math.random() * a.length)];
};
}

window.alert(new myClass());
Irrelevant code - what does it prove?

It has proven that Google Groups and your irony detector are borken.


PointedEars
 
U

Ugo

The best way of doing something depends at least in part on what it is
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
A generic way to create a singleton object with global access is to
use a object literal.

var someSingleton = {
someProperty: function() {},
someOtherProperty: 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
};
})();
 
V

VK

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
};

})();

The way I'm using most often - without any claims that it is the best
out of anything:

function MySingleton() {
if (this == self) {
window.alert('Conctructor called as a function');
return MySingleton;
}
else if (
!!($isInstantiated.flag) ||
(this instanceof MySingleton) ||
(MySingleton.isPrototypeOf(this))
) {
window.alert('Only one instance is allowed');
return mySingleton;
}
else {
// instantiate your singleton
// with methods and properties
// ...
this.toString = $toString;
$isInstantiated.flag = true;
}
function $isInstantiated() {
return arguments.callee.flag;
}
function $toString() {
return ''.concat(
'function mySingleton() {\n',
' [native code]\n',
'}'
);
}
}

The benefits as I see them:
1) It is much lesser convoluted as function expression ways.
Respectively it is easier to read, to maintain and to avoid parasite
closures.
2) It allows to distinct different "not allowed" situation so to
provide more informative errors - in a real case window.alert replaced
by throw new Error of course.
3) it prevents or at least makes much harder to use reliably runtime
cloning over source code dumping and reusing in eval or new Function.
 
P

Peter Michaux

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
 
V

VK

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
};

The way I'm using most often - without any claims that it is the best
out of anything:

function MySingleton() {
if (this == self) {
window.alert('Conctructor called as a function');
return MySingleton;
}
else if (
!!($isInstantiated.flag) ||
(this instanceof MySingleton) ||
(MySingleton.isPrototypeOf(this))
) {
window.alert('Only one instance is allowed');
return mySingleton;
}
else {
// instantiate your singleton
// with methods and properties
// ...
this.toString = $toString;
$isInstantiated.flag = true;
}
function $isInstantiated() {
return arguments.callee.flag;
}
function $toString() {
return ''.concat(
'function mySingleton() {\n',
' [native code]\n',
'}'
);
}

}

The benefits as I see them:
1) It is much lesser convoluted as function expression ways.
Respectively it is easier to read, to maintain and to avoid parasite
closures.
2) It allows to distinct different "not allowed" situation so to
provide more informative errors - in a real case window.alert replaced
by throw new Error of course.
3) it prevents or at least makes much harder to use reliably runtime
cloning over source code dumping and reusing in eval or new Function.

A few errors made while pulling out the code and readjusting for
posting, sorry. The corrected version would be:

function MySingleton() {
if (this == self) {
window.alert('Conctructor called as a function');
return MySingleton;
}
else if (
!!($isInstantiated.flag) &&
((this instanceof MySingleton) ||
(MySingleton.isPrototypeOf(this)))
) {
window.alert('Only one instance is allowed');
return MySingleton;
}
else {
// instantiate your singleton
// with methods and properties
// ...
this.toString = $toString;
$isInstantiated.flag = true;
}
function $isInstantiated() {
return arguments.callee.flag;
}
function $toString() {
return ''.concat(
'function mySingleton() {\n',
' [native code]\n',
'}'
);
}
}
 
U

Ugo

[cut]
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.

But, reconsidering...
it's applicatively equal to my original code:
[by step]
it'was the same:


var singleton = (function()
{
// "privare" prop
var a = 1;
// "private" method
function b( )
{
alert('hi');
}
// Obj
return {
hi : b,
a: a
};
})();

that is analog to:

var singleton = (function()
{
// "privare" prop
var a = 1;
// "private" method
function b( )
{
alert('hi');
}
// Obj
return new function()
{
this.hi = b;
this.a = a;
};
})();

my origina code
 
P

Peter Michaux

[cut]


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.

But, reconsidering...
it's applicatively equal to my original code:
[by step]
it'was the same:

var singleton = (function()
{
// "privare" prop
var a = 1;
// "private" method
function b( )
{
alert('hi');
}
// Obj
return {
hi : b,
a: a
};

})();

that is analog to:

var singleton = (function()
{
// "privare" prop
var a = 1;
// "private" method
function b( )
{
alert('hi');
}
// Obj
return new function()
{
this.hi = b;
this.a = a;
};

})();

my origina code


Given the original post...

Hi guys,

how do you make a singleton access class?

Do you know a better way of this one:

[snip]

I believe I have presented several options that I think are better and
actually are standard JavaScript patterns?

What is it you want from the group?

Peter
 
U

Ugo

[cut]
[snip]

I believe I have presented several options that I think are better and
actually are standard JavaScript patterns?

What is it you want from the group?

Sorry, I didn't want to seem ungrateful :(
I'm very happy about "several options" were listed...

In addition, I wanted to adopt the guide lines of GoF's pattern, and
parhaps I succeed:


var SingletonClass;
(function()
{
var instance;
SingletonClass = function( )
{
if( this == window )
{
alert( 'This is no function!' );
return;
}
// else if( this.prototype != SingletonClass.prototype )
else if( ! ( this instanceof SingletonClass ) )
{
alert( 'Che cavolo stai dicendo Willis!' );
return;
}
else if( instance )
return instance;
else
instance = this;

this.$ = 'hi';
this.f = function()
{
alert( this.$ );
}
}
SingletonClass.getInstance = function( )
{
return instance || ( instance = new SingletonClass( ) );
}
})();
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,774
Messages
2,569,599
Members
45,177
Latest member
OrderGlucea
Top