V
VK
The solution is unnecessary convoluted by extra closures not bearing
any functional load. That is IMHO and OK if someone just loves
closures so collecting different species of them like orchids
The possible failure point is in "not allowed" checks like:
If a function is called as constructor, thus in the context "new
SingletonClass" or "new DerivedSingletonClass", then the return value
_must_ be an object. If it tries to return a primitive value then such
return value will be silently disregarded and the current value of
"this" will be returned instead. This behavior is by design and by
ECMAScript specs.
This way say having:
else if (
!!($isInstantiated.flag) &&
((this instanceof MySingleton) ||
(MySingleton.isPrototypeOf(this)))
) {
window.alert('Only one instance is allowed');
// WRONG:
return;
}
}
your constructor doesn't return undefined as one would possibly expect
but "this" value, so still a new instance just not fully initialized
by properties and methods.
To overcome that in "not allowed" situations you have either:
1) return a reference to the constructor:
return SingletonClass;
2) throw Error _and_ return a reference to the constructor to
eliminate any possible "resume next" attempts.
3) return false wrapped into Boolean object for further condition
checks:
return new Boolean;
any functional load. That is IMHO and OK if someone just loves
closures so collecting different species of them like orchids
The possible failure point is in "not allowed" checks like:
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;
}
If a function is called as constructor, thus in the context "new
SingletonClass" or "new DerivedSingletonClass", then the return value
_must_ be an object. If it tries to return a primitive value then such
return value will be silently disregarded and the current value of
"this" will be returned instead. This behavior is by design and by
ECMAScript specs.
This way say having:
else if (
!!($isInstantiated.flag) &&
((this instanceof MySingleton) ||
(MySingleton.isPrototypeOf(this)))
) {
window.alert('Only one instance is allowed');
// WRONG:
return;
}
}
your constructor doesn't return undefined as one would possibly expect
but "this" value, so still a new instance just not fully initialized
by properties and methods.
To overcome that in "not allowed" situations you have either:
1) return a reference to the constructor:
return SingletonClass;
2) throw Error _and_ return a reference to the constructor to
eliminate any possible "resume next" attempts.
3) return false wrapped into Boolean object for further condition
checks:
return new Boolean;