Re: A Singleton with Inheritance
Available news archives: comp.lang.tcl - comp.lang.python - comp.security.firewalls - sci.crypt - comp.lang.php - comp.lang.javascript
Google
 
Web news.hping.org


comp.lang.javascript archive

Re: A Singleton with Inheritance

From: Lasse Reichstein Nielsen <lrn@hotpop.com>
Date: Fri Dec 09 2005 - 02:49:24 CET

Kevin Newman <CaptainN@unFocus.com> writes:

> I have been playing around with a couple of ways to add inheritance to
> a JavaScript singleton pattern.

Does the singleton (anti-)pattern make sense at all in a prototype based
language.

In a class based language, a singleton is a type for which there is
only ever one value, i.e., a non-inheritable class with only one
instance.

In a prototype based language, there are no classes and no
corresponding type. Any object can be used as a prototype,
so the singleton behavior cannot be enforced.

> As far as I'm aware, using an anonymous constructor to create a
> singleton does not allow any kind of inheritance:
>
> singletonObj = new function() {
> this.prop = true;
> }

While this creates an object with a prototype different from
Object.prototype, there isn't really any advantage over just
doing
 singletonObj = { prop:true };

> Here are two ways to create a singleton with inheritance:
>
> // class to inherit from
> SuperClass = function() {
> this.superProp = true;
> }

So we restrict ourselves to constructors that can be seen as
representatives of the instances they create, i.e., as pseudo classes.

> // second way
... both ways work the same, just using different scoping mechanisms ...

> singletonObj = (function() {
> function SingletonClass() {
> this.prop = true;
> }
> SingletonClass.prototype = new SuperClass();
> return new SingletonClass();
> })();

Here the singletonObj uses an instance of SuperClass as its prototype.

Notice that this is not similar to class based inheritance, where
you inherit from the class. It is prototype based inheritance,
where you inherit from a specific instance.

Again I fail to see the advantage over
 singletonObj = new SuperClass();
All that happens is that one extra object is put into the
prototype chain.

It is impossible to enforce the singleton pattern, since you can
always create a object inheriting from the existing one:

 function clone(o) {
   function dummy(){};
   dummpy.prototype = o;
   return new dummy();
 }

 notSoSingletonObj = clone(singletonObj);

/L

-- 
Lasse Reichstein Nielsen  -  lrn@hotpop.com
 DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
  'Faith without judgement merely degrades the spirit divine.'
Received on Sun Dec 11 14:34:24 2005