How to emulate Javascript `super` so `new.target` is defined? - javascript

I'm attempting to emulate this javascript without using the ES6 keywords (e.g. without class, super or extends):
class Foo {
constructor() {
if (!new.target)
console.log('Foo() must be called with new');
}
}
class Bar extends Foo {
constructor() {
super(...arguments);
}
}
var bar = new Bar();
var barIsFoo = bar instanceof Foo;
console.log(barIsFoo); // true
I got this far, but they're not equivalent. The following throws (I log instead) while the latter does not:
function Foo() {
if (!new.target)
console.log('Foo() must be called with new');
}
function Bar() {
Foo.apply(this, arguments)
}
Bar.prototype = Object.create(Foo.prototype);
Bar.prototype.constructor = Bar;
var bar = new Bar();
var barIsFoo = bar instanceof Foo;
console.log(barIsFoo);
So, how do I emulate providing a value for new.target when I call into Foo from Bar?
So, seems there's no apply or call that allows passing the new.target. I suppose that would defeat the purpose of new.target (though the fact that everything in JS is public really appealed to me).
So to emulate in ES5 we'd need to add something.
One solution in an answer below allocates a new object.
This solution adds new functions construct which can be chained as usual in ES5 and leave the function itself free to do nothing more than check if it's being used as a constructor.
function Foo() {
if (!new.target)
throw 'Foo() must be called with new';
console.log('Foo new check');
Foo.prototype.construct.apply(this, arguments);
}
Foo.prototype.construct = function() {
console.log('Foo construction logic');
}
function Bar() {
if (!new.target)
throw 'Bar() must be called with new';
console.log('Bar new check');
Bar.prototype.construct.apply(this, arguments);
}
Bar.prototype = Object.create(Foo.prototype);
Bar.prototype.constructor = Bar;
Bar.prototype.construct = function() {
// super()
Foo.prototype.construct.apply(this, arguments);
console.log('Bar construction logic');
}
var bar = new Bar();
var barIsFoo = bar instanceof Foo;
console.log(barIsFoo);
Bottom line, it appears ES6 features not not just syntactic sugar over ES5. Of course, they could just add a Function.prototype.super(target, arguments, newTarget) and then we could just use that. I hope they do!
Only super can call a function in Javascript and have this not be available immediately. So super is unique. And super can only be called in the context of a constructor which can only be used in the context of a class. Sooo all those key words are necessary to make super work. So Javascript has introduced a very specific object oriented feature. Looks like building a language on top of the idea of a "prototype" has it's limits.
Which is a shame...
I wonder why, all of a sudden, javascript decided to enforce this one invariant. That this is not available before the super call. Why not just make super a short hand for BaseType.prototype.constructor.call(this, ...). Why not allow it to be invoked more than once? We can blow our toes off so many other ways in Javascript, why start enforcing things now?
Well, anyway...
So, double bottom line, there exists a early bound Javascript call super that has no late bound equivalent (unlike, for example, foo.bar() which can be called late(r)bound via bar.call('foo')).

Use Object.assign to assign the parent constructor's new Foo(...arguments) to the instance:
function Foo(arg) {
if (!new.target)
throw 'Foo() must be called with new';
this.arg = arg;
this.fooProp = 'fooProp';
}
function Bar() {
Object.assign(
this,
new Foo(...arguments)
);
this.barProp = 'barProp';
}
Bar.prototype = Object.create(Foo.prototype);
Bar.prototype.constructor = Bar;
var bar = new Bar('abc');
var barIsFoo = bar instanceof Foo;
console.log(barIsFoo);
console.log(bar);
But new Foo(...arguments) is ES6 syntax. To translate that to ES5, instead use
new (Function.prototype.bind.apply(Foo, [null, ...arguments]))()
(which takes care of the new part), which again transpiles down to
new (Function.prototype.bind.apply(Foo, [null].concat(Array.prototype.slice.call(arguments))))()
function Foo(arg) {
if (!new.target)
throw 'Foo() must be called with new';
this.arg = arg;
this.fooProp = 'fooProp';
}
function Bar() {
Object.assign(
this,
new (Function.prototype.bind.apply(Foo, [null].concat(Array.prototype.slice.call(arguments))))()
);
this.barProp = 'barProp';
}
Bar.prototype = Object.create(Foo.prototype);
Bar.prototype.constructor = Bar;
var bar = new Bar('abc');
var barIsFoo = bar instanceof Foo;
console.log(barIsFoo);
console.log(bar);

ES6 class syntax is not syntax sugar for ES5, but it is pretty much syntax sugar for other ES6 functionality.
class Bar extends Foo {
constructor() {
super(...arguments);
}
}
is pretty similar to if you did
let Bar = function(...args) {
const _this = Reflect.construct(Object.getPrototypeOf(Bar), args, new.target);
return _this;
};
Object.setPrototypeOf(Bar, Foo);
Object.setPrototypeOf(Bar.prototype, Foo.prototype);
where Reflect.construct constructs and object with a given new.target value and calls a given constructor with a set of arguments.

To write abstract classes, you need to make sure that the constructor of the parent class is called in the context of the prototype of the called class.
To do this, ES6 introduced "Reflect.construct".
For ES5, you can implement your own "crutch".
// Reflect.construct simulation for ES5
class Reflect2 {
static construct(TargetClass,args,ProtoClass){
let oldProto= TargetClass.prototype;
let desc=Object.getOwnPropertyDescriptor(TargetClass,'prototype');
if(desc.hasOwnProperty('value') && desc.writable===false){
if(desc.configurable===true){
desc.writable=true;
Object.defineProperty(TargetClass,'prototype',desc);
}
}
TargetClass.prototype=ProtoClass.prototype;
let self=new (Function.prototype.bind.apply(TargetClass,args));
TargetClass.prototype=oldProto;
return self;
}
}
function ParentClass(){
}
ParentClass.prototype.constructor=ParentClass;
function MyClass(){
if(new.target===undefined){throw Error();}
let self=Reflect2.construct (ParentClass,[],new.target);
// your code
return self;
}
MyClass.prototype=Object.create(ParentClass.prototype,{
constructor:{
value:MyClass
}
});
let a=new MyClass();
console.log(Object.getPrototypeOf(a)===MyClass.prototype);
"super" in ES6 is the same "this", but in the context of the parent prototype. For example, when we bind an object to a function via "bind ()", here we bind object "this" only to the prototype object.
"super" can be implemented in 2 ways:
through prototype scanning, and binding to methods and reactive properties of the 'this' object;
via Proxy object
Emulation 'super' in ES6
via Proxy object
/**
* #param {object} self - this object
* #param {function} ProtoClass - the class to observe.
Usually the current class for which methods are being written.
* #param {function} [new_target] used in the constructor.
If not passed, then the default will be the prototype constructor for "self"
(Object.getPrototyprOf(self).constructor).
* #param {boolean} [bindSelf] - if true, then the methods and reactive properties
of the parent will work in the context of self, if false, then the methods and
reactive properties will work within the framework of the object in which they
are called (i.e. within the Proxy object).
*/
function Super(self,ProtoClass,new_target,bindSelf=false){
let parentProto=Object.getPrototypeOf(ProtoClass.prototype);
let descs={};
// collect descriptors of all prototypes
do {
let buf=Object.getOwnPropertyDescriptors(parentProto);
for(let prop of Object.keys(buf)){
if(!Object.prototype.hasOwnProperty.call(descs,prop)){
descs[prop]=buf[prop];
}
}
parentProto=Object.getPrototypeOf(parentProto);
}while (parentProto!==null);
// we define the control object
let answer={};
let new_obj=function (...args){
let ParentClass=Object.getPrototypeOf(ProtoClass.prototype).constructor;
if(ParentClass===Object || ProtoClass===ParentClass){
return self;
}
new_target=new_target??Object.getPrototypeOf(self).constructor;
return Reflect.construct(ParentClass,args,new_target);
}
let parent=new Proxy(self,{
get(target,prop){
let desc=descs[prop];
if(desc===undefined){
return;
}
if(desc.hasOwnProperty('value')){
if(bindSelf && typeof desc.value==='function'){
return desc.value.bind(target);
}
return desc.value;
} else
if(desc.hasOwnProperty('get')){
return desc.get.call(target);
}
},
set(target,prop,value){
let desc=descs[prop];
if(desc===undefined || desc.hasOwnProperty('value')){
target[prop]=value;
return true;
}
if(desc.hasOwnProperty('set')){
desc.set.call(target,value);
return true;
}
}
});
Object.defineProperties(answer,{
new:{
value:new_obj
},
parent:{
value:parent
}
});
return answer;
}
How to use
function A(...args){
}
A.prototype.method=function(){
console.log('hello',this);
return this;
}
A.prototype.constructor=A;
function B(...args){
if(new.target===undefined){throw Error();}
let _super=Super(this,B,new.target);
let self= _super.new(...args);
let b=_super.parent.method(); // return proxy object
/*
in this case, all execution inside the method will occur as if this has a parent prototype.
*/
console.log(b===this);// false
return self;
}
B.prototype=Object.create(A.prototype);
B.prototype.constructor=B;
B.prototype.method=function(){
console.log('bay');
return this;
}
let b=new B();
or
function A(...args){
}
A.prototype.method=function(){
console.log('hello',this);
return this;
}
A.prototype.constructor=A;
function B(...args){
if(new.target===undefined){throw Error();}
/*
we want the methods to execute against the "this" context
and not in the "new Proxy ('this', {})" context
*/
let _super=Super(this,B,new.target,true);// arg[3] true
let self= _super.new(...args);
let b=_super.parent.method(); // return this object
console.log(b===this);// true
return self;
}
B.prototype=Object.create(A.prototype);
B.prototype.constructor=B;
B.prototype.method=function(){
console.log('bay');
return this;
}
let b=new B();
for ES5 Proxies can be replaced with a regular object, where “this” through “bind” is bound to methods.
function Super(self,ProtoClass,new_target){
let parentProto=Object.getPrototypeOf(ProtoClass.prototype);
let parent={};
// properties all prototypes
do {
let buf=Object.getOwnPropertyDescriptors(parentProto);
for(let prop of Object.keys(buf)){
if(!Object.prototype.hasOwnProperty.call(parent,prop)){
let desc=buf[prop];
if(buf[prop].hasOwnProperty('get') ){
desc.get=buf[prop].get.bind(self);
}
if(buf[prop].hasOwnProperty('set') ){
desc.set=buf[prop].set.bind(self);
}
if(buf[prop].hasOwnProperty('value') ){
if (typeof buf[prop].value === 'function') {
desc.value=buf[prop].value.bind(self);
} else{
delete desc.value;
delete desc.writable;
desc.get=function (){
return buf[prop];
};
desc.set=function(v){
self[prop]=v;
};
}
}
Object.defineProperty(parent,prop,desc);
}
}
parentProto=Object.getPrototypeOf(parentProto);
} while (parentProto!==null);
// we define the control object
let answer={};
let new_obj=function (){
let ParentClass=Object.getPrototypeOf(ProtoClass.prototype).constructor;
if(ParentClass===Object || ProtoClass===ParentClass){
return self;
}
new_target=new_target??Object.getPrototypeOf(self).constructor;
// We described the "Reflect.construct method" above. see Reflect2.construct
return Reflect.construct(ParentClass,Array.prototype.slice.call(arguments),new_target);
}
Object.defineProperties(answer,{
new:{
value:new_obj
},
parent:{
value:parent
}
});
return answer;
}
Example
function A(...args){
}
A.prototype.method=function(){
console.log('hello',this);
return this;
}
A.prototype.constructor=A;
function B(...args){
if(new.target===undefined){throw Error();}
let _super=Super(this,B,new.target);
let self= _super.new(...args);
let b=_super.parent.method();
console.log(b===this);
return self;
}
B.prototype=Object.create(A.prototype);
B.prototype.constructor=B;
B.prototype.method=function(){
console.log('bay');
return this;
}
let b=new B();

The purpose of using if (!new.target) is to check if the Foo is called with new(as a constructor), in which case we can just use if(this instanceof Foo) instead.
this could be an instance of Foo or Bar, and whether you call new Foo() or Foo.apply(this), the this instanceof Foo can always return true while it will return false if you just call Foo()(without new or apply/call).
Try this:
function Foo() {
if (!this instanceof Foo)
console.log('Foo() must be called with new');
}
function Bar() {
Foo.apply(this, arguments)
}
Bar.prototype = Object.create(Foo.prototype);
Bar.prototype.constructor = Bar;
var bar = new Bar();
var barIsFoo = bar instanceof Foo;
console.log(barIsFoo);

Related

TypeError: can't access property "constructor", object is undefined [duplicate]

What is the simplest/cleanest way to implement the singleton pattern in JavaScript?
I think the easiest way is to declare a simple object literal:
var myInstance = {
method1: function () {
// ...
},
method2: function () {
// ...
}
};
If you want private members on your singleton instance, you can do something like this:
var myInstance = (function() {
var privateVar = '';
function privateMethod () {
// ...
}
return { // public interface
publicMethod1: function () {
// All private members are accessible here
},
publicMethod2: function () {
}
};
})();
This has been called the module pattern, and it basically allows you to encapsulate private members on an object, by taking advantage of the use of closures.
If you want to prevent the modification of the singleton object, you can freeze it, using the ES5 Object.freeze method.
That will make the object immutable, preventing any modification to the its structure and values.
If you are using ES6, you can represent a singleton using ES Modules very easily, and you can even hold private state by declaring variables at the module scope:
// my-singleton.js
const somePrivateState = []
function privateFn () {
// ...
}
export default {
method1() {
// ...
},
method2() {
// ...
}
}
Then you can simply import the singleton object to use it:
import myInstance from './my-singleton.js'
// ...
I think the cleanest approach is something like:
var SingletonFactory = (function(){
function SingletonClass() {
//do stuff
}
var instance;
return {
getInstance: function(){
if (instance == null) {
instance = new SingletonClass();
// Hide the constructor so the returned object can't be new'd...
instance.constructor = null;
}
return instance;
}
};
})();
Afterwards, you can invoke the function as
var test = SingletonFactory.getInstance();
I'm not sure I agree with the module pattern being used as a replacement for a singleton pattern. I've often seen singletons used and abused in places where they're wholly unnecessary, and I'm sure the module pattern fills many gaps where programmers would otherwise use a singleton. However, the module pattern is not a singleton.
Module pattern:
var foo = (function () {
"use strict";
function aPrivateFunction() {}
return { aPublicFunction: function () {...}, ... };
}());
Everything initialized in the module pattern happens when Foo is declared. Additionally, the module pattern can be used to initialize a constructor, which could then be instantiated multiple times. While the module pattern is the right tool for many jobs, it's not equivalent to a singleton.
Singleton pattern:
short form
var Foo = function () {
"use strict";
if (Foo._instance) {
// This allows the constructor to be called multiple times
// and refer to the same instance. Another option is to
// throw an error.
return Foo._instance;
}
Foo._instance = this;
// Foo initialization code
};
Foo.getInstance = function () {
"use strict";
return Foo._instance || new Foo();
}
long form, using module pattern
var Foo = (function () {
"use strict";
var instance; //prevent modification of "instance" variable
function Singleton() {
if (instance) {
return instance;
}
instance = this;
//Singleton initialization code
}
// Instance accessor
Singleton.getInstance = function () {
return instance || new Singleton();
}
return Singleton;
}());
In both versions of the singleton pattern that I've provided, the constructor itself can be used as the accessor:
var a,
b;
a = new Foo(); // Constructor initialization happens here
b = new Foo();
console.log(a === b); //true
If you don't feel comfortable using the constructor this way, you can throw an error in the if (instance) statement, and stick to using the long form:
var a,
b;
a = Foo.getInstance(); // Constructor initialization happens here
b = Foo.getInstance();
console.log(a === b); // true
I should also mention that the singleton pattern fits well with the implicit constructor function pattern:
function Foo() {
if (Foo._instance) {
return Foo._instance;
}
// If the function wasn't called as a constructor,
// call it as a constructor and return the result
if (!(this instanceof Foo)) {
return new Foo();
}
Foo._instance = this;
}
var f = new Foo(); // Calls Foo as a constructor
-or-
var f = Foo(); // Also calls Foo as a constructor
In ES6 the right way to do this is:
class MyClass {
constructor() {
if (MyClass._instance) {
throw new Error("Singleton classes can't be instantiated more than once.")
}
MyClass._instance = this;
// ... Your rest of the constructor code goes after this
}
}
var instanceOne = new MyClass() // Executes succesfully
var instanceTwo = new MyClass() // Throws error
Or, if you don't want an error to be thrown on the second instance creation, you can just return the last instance, like so:
class MyClass {
constructor() {
if (MyClass._instance) {
return MyClass._instance
}
MyClass._instance = this;
// ... Your rest of the constructor code goes after this
}
}
var instanceOne = new MyClass()
var instanceTwo = new MyClass()
console.log(instanceOne === instanceTwo) // Logs "true"
In ECMAScript 2015 (ES6):
class Singleton {
constructor () {
if (!Singleton.instance) {
Singleton.instance = this
}
// Initialize object
return Singleton.instance
}
// Properties & Methods
}
const instance = new Singleton()
Object.freeze(instance)
export default instance
If you're using node.JS then you can take advantage of node.JS caching mechanism and your Singleton will be as simple as:
class Singleton {
constructor() {
this.message = 'I am an instance';
}
}
module.exports = new Singleton();
Please note that we export not the class Singleton but instance Singleton().
Node.JS will cache and reuse the same object each time it’s required.
For more details please check: Node.JS and Singleton Pattern
The following works in Node.js version 6:
class Foo {
constructor(msg) {
if (Foo.singleton) {
return Foo.singleton;
}
this.msg = msg;
Foo.singleton = this;
return Foo.singleton;
}
}
We test:
const f = new Foo('blah');
const d = new Foo('nope');
console.log(f); // => Foo { msg: 'blah' }
console.log(d); // => Foo { msg: 'blah' }
The simplest/cleanest for me means also simply to understand and no bells & whistles as are much discussed in the Java version of the discussion:
What is an efficient way to implement a singleton pattern in Java?
The answer that would fit simplest/cleanest best there from my point of view is:
Jonathan's answer to What is an efficient way to implement a singleton pattern in Java?
And it can only partly be translated to JavaScript. Some of the difference in JavaScript are:
constructors can't be private
Classes can't have declared fields
But given the latest ECMA syntax, it is possible to get close with:
Singleton pattern as a JavaScript class example
class Singleton {
constructor(field1,field2) {
this.field1=field1;
this.field2=field2;
Singleton.instance=this;
}
static getInstance() {
if (!Singleton.instance) {
Singleton.instance=new Singleton('DefaultField1','DefaultField2');
}
return Singleton.instance;
}
}
Example Usage
console.log(Singleton.getInstance().field1);
console.log(Singleton.getInstance().field2);
Example Result
DefaultField1
DefaultField2
If you want to use classes:
class Singleton {
constructor(name, age) {
this.name = name;
this.age = age;
if(this.constructor.instance)
return this.constructor.instance;
this.constructor.instance = this;
}
}
let x = new Singleton('s', 1);
let y = new Singleton('k', 2);
Output for the above will be:
console.log(x.name, x.age, y.name, y.age) // s 1 s 1
Another way of writing Singleton using function
function AnotherSingleton (name,age) {
this.name = name;
this.age = age;
if(this.constructor.instance)
return this.constructor.instance;
this.constructor.instance = this;
}
let a = new AnotherSingleton('s', 1);
let b = new AnotherSingleton('k', 2);
Output for the above will be:
console.log(a.name, a.age, b.name, b.age) // s 1 s 1
There is more than one way to skin a cat :) Depending on your taste or specific need you can apply any of the proposed solutions. I personally go for Christian C. Salvadó's first solution whenever possible (when you don't need privacy).
Since the question was about the simplest and cleanest, that's the winner. Or even:
var myInstance = {}; // Done!
This (quote from my blog)...
var SingletonClass = new function() {
this.myFunction() {
// Do stuff
}
this.instance = 1;
}
doesn't make much sense (my blog example doesn't either) because it doesn't need any private variables, so it's pretty much the same as:
var SingletonClass = {
myFunction: function () {
// Do stuff
},
instance: 1
}
I deprecate my answer, see my other one.
Usually the module pattern (see Christian C. Salvadó's answer) which is not the singleton pattern is good enough. However, one of the features of the singleton is that its initialization is delayed till the object is needed. The module pattern lacks this feature.
My proposition (CoffeeScript):
window.singleton = (initializer) ->
instance = undefined
() ->
return instance unless instance is undefined
instance = initializer()
Which compiled to this in JavaScript:
window.singleton = function(initializer) {
var instance;
instance = void 0;
return function() {
if (instance !== void 0) {
return instance;
}
return instance = initializer();
};
};
Then I can do following:
window.iAmSingleton = singleton(function() {
/* This function should create and initialize singleton. */
alert("creating");
return {property1: 'value1', property2: 'value2'};
});
alert(window.iAmSingleton().property2); // "creating" will pop up; then "value2" will pop up
alert(window.iAmSingleton().property2); // "value2" will pop up but "creating" will not
window.iAmSingleton().property2 = 'new value';
alert(window.iAmSingleton().property2); // "new value" will pop up
I got this example from the *JavaScript Patterns
Build Better Applications with Coding and Design Patterns book (by Stoyan Stefanov). In case you need some simple implementation class like a singleton object, you can use an immediate function as in the following:
var ClassName;
(function() {
var instance;
ClassName = function ClassName() {
// If the private instance variable is already initialized, return a reference
if(instance) {
return instance;
}
// If the instance is not created, save a pointer of the original reference
// to the private instance variable.
instance = this;
// All constructor initialization will be here
// i.e.:
this.someProperty = 0;
this.someMethod = function() {
// Some action here
};
};
}());
And you can check this example by following test case:
// Extending defined class like singleton object using the new prototype property
ClassName.prototype.nothing = true;
var obj_1 = new ClassName();
// Extending the defined class like a singleton object using the new prototype property
ClassName.prototype.everything = true;
var obj_2 = new ClassName();
// Testing makes these two objects point to the same instance
console.log(obj_1 === obj_2); // Result is true, and it points to the same instance object
// All prototype properties work
// no matter when they were defined
console.log(obj_1.nothing && obj_1.everything
&& obj_2.nothing && obj_2.everything); // Result true
// Values of properties which are defined inside of the constructor
console.log(obj_1.someProperty); // Outputs 0
console.log(obj_2.someProperty); // Outputs 0
// Changing property value
obj_1.someProperty = 1;
console.log(obj_1.someProperty); // Output 1
console.log(obj_2.someProperty); // Output 1
console.log(obj_1.constructor === ClassName); // Output true
This approach passes all test cases while a private static implementation will fail when a prototype extension is used (it can be fixed, but it will not be simple) and a public static implementation less advisable due to an instance is exposed to the public.
jsFiddly demo.
Short answer:
Because of the non-blocking nature of JavaScript, singletons in JavaScript are really ugly in use. Global variables will give you one instance through the whole application too without all these callbacks, and module pattern gently hides internals behind the interface. See Christian C. Salvadó's answer.
But, since you wanted a singleton…
var singleton = function(initializer) {
var state = 'initial';
var instance;
var queue = [];
var instanceReady = function(createdInstance) {
state = 'ready';
instance = createdInstance;
while (callback = queue.shift()) {
callback(instance);
}
};
return function(callback) {
if (state === 'initial') {
state = 'waiting';
queue.push(callback);
initializer(instanceReady);
} else if (state === 'waiting') {
queue.push(callback);
} else {
callback(instance);
}
};
};
Usage:
var singletonInitializer = function(instanceReady) {
var preparedObject = {property: 'value'};
// Calling instanceReady notifies the singleton that the instance is ready to use
instanceReady(preparedObject);
}
var s = singleton(singletonInitializer);
// Get the instance and use it
s(function(instance) {
instance.doSomething();
});
Explanation:
Singletons give you more than just one instance through the whole application: their initialization is delayed till the first use. This is really a big thing when you deal with objects whose initialization is expensive. Expensive usually means I/O and in JavaScript I/O always mean callbacks.
Don't trust answers which give you interface like instance = singleton.getInstance(), they all miss the point.
If they don't take a callback to be run when an instance is ready, then they won't work when the initializer does I/O.
Yeah, callbacks always look uglier than a function call which immediately returns an object instance. But again: when you do I/O, callbacks are obligatory. If you don't want to do any I/O, then instantiation is cheap enough to do it at program start.
Example 1, cheap initializer:
var simpleInitializer = function(instanceReady) {
console.log("Initializer started");
instanceReady({property: "initial value"});
}
var simple = singleton(simpleInitializer);
console.log("Tests started. Singleton instance should not be initalized yet.");
simple(function(inst) {
console.log("Access 1");
console.log("Current property value: " + inst.property);
console.log("Let's reassign this property");
inst.property = "new value";
});
simple(function(inst) {
console.log("Access 2");
console.log("Current property value: " + inst.property);
});
Example 2, initialization with I/O:
In this example, setTimeout fakes some expensive I/O operation. This illustrates why singletons in JavaScript really need callbacks.
var heavyInitializer = function(instanceReady) {
console.log("Initializer started");
var onTimeout = function() {
console.log("Initializer did his heavy work");
instanceReady({property: "initial value"});
};
setTimeout(onTimeout, 500);
};
var heavy = singleton(heavyInitializer);
console.log("In this example we will be trying");
console.log("to access singleton twice before it finishes initialization.");
heavy(function(inst) {
console.log("Access 1");
console.log("Current property value: " + inst.property);
console.log("Let's reassign this property");
inst.property = "new value";
});
heavy(function(inst) {
console.log("Access 2. You can see callbacks order is preserved.");
console.log("Current property value: " + inst.property);
});
console.log("We made it to the end of the file. Instance is not ready yet.");
Christian C. Salvadó's and zzzzBov's answer have both given wonderful answers, but just to add my own interpretation based on my having moved into heavy Node.js development from PHP/Zend Framework where singleton patterns were common.
The following, comment-documented code is based on the following requirements:
one and only one instance of the function object may be instantiated
the instance is not publicly available and may only be accessed through a public method
the constructor is not publicly available and may only be instantiated if there is not already an instance available
the declaration of the constructor must allow its prototype chain to be modified. This will allow the constructor to inherit from other prototypes, and offer "public" methods for the instance
My code is very similar to zzzzBov's answer except I've added a prototype chain to the constructor and more comments that should help those coming from PHP or a similar language translate traditional OOP to JavaScript's prototypical nature. It may not be the "simplest" but I believe it is the most proper.
// Declare 'Singleton' as the returned value of a self-executing anonymous function
var Singleton = (function () {
"use strict";
// 'instance' and 'constructor' should not be available in a "public" scope
// here they are "private", thus available only within
// the scope of the self-executing anonymous function
var _instance=null;
var _constructor = function (name) {
this.name = name || 'default';
}
// Prototypes will be "public" methods available from the instance
_constructor.prototype.getName = function () {
return this.name;
}
// Using the module pattern, return a static object
// which essentially is a list of "public static" methods
return {
// Because getInstance is defined within the same scope
// it can access the "private" 'instance' and 'constructor' vars
getInstance:function (name) {
if (!_instance) {
console.log('creating'); // This should only happen once
_instance = new _constructor(name);
}
console.log('returning');
return _instance;
}
}
})(); // Self execute
// Ensure 'instance' and 'constructor' are unavailable
// outside the scope in which they were defined
// thus making them "private" and not "public"
console.log(typeof _instance); // undefined
console.log(typeof _constructor); // undefined
// Assign instance to two different variables
var a = Singleton.getInstance('first');
var b = Singleton.getInstance('second'); // passing a name here does nothing because the single instance was already instantiated
// Ensure 'a' and 'b' are truly equal
console.log(a === b); // true
console.log(a.getName()); // "first"
console.log(b.getName()); // Also returns "first" because it's the same instance as 'a'
Note that technically, the self-executing anonymous function is itself a singleton as demonstrated nicely in the code provided by Christian C. Salvadó. The only catch here is that it is not possible to modify the prototype chain of the constructor when the constructor itself is anonymous.
Keep in mind that to JavaScript, the concepts of “public” and “private” do not apply as they do in PHP or Java. But we have achieved the same effect by leveraging JavaScript’s rules of functional scope availability.
You could just do:
var singleton = new (function() {
var bar = 123
this.foo = function() {
// Whatever
}
})()
I think I have found the cleanest way to program in JavaScript, but you'll need some imagination. I got this idea from a working technique in the book JavaScript: The Good Parts.
Instead of using the new keyword, you could create a class like this:
function Class()
{
var obj = {}; // Could also be used for inheritance if you don't start with an empty object.
var privateVar;
obj.publicVar;
obj.publicMethod = publicMethod;
function publicMethod(){}
function privateMethod(){}
return obj;
}
You can instantiate the above object by saying:
var objInst = Class(); // !!! NO NEW KEYWORD
Now with this work method in mind, you could create a singleton like this:
ClassSingleton = function()
{
var instance = null;
function Class() // This is the class like the above one
{
var obj = {};
return obj;
}
function getInstance()
{
if( !instance )
instance = Class(); // Again no 'new' keyword;
return instance;
}
return { getInstance : getInstance };
}();
Now you can get your instance by calling
var obj = ClassSingleton.getInstance();
I think this is the neatest way as the complete "Class" is not even accessible.
The clearest answer should be this one from the book Learning JavaScript Design Patterns by Addy Osmani.
var mySingleton = (function () {
// Instance stores a reference to the singleton
var instance;
function init() {
// Singleton
// Private methods and variables
function privateMethod(){
console.log( "I am private" );
}
var privateVariable = "I'm also private";
var privateRandomNumber = Math.random();
return {
// Public methods and variables
publicMethod: function () {
console.log( "The public can see me!" );
},
publicProperty: "I am also public",
getRandomNumber: function() {
return privateRandomNumber;
}
};
};
return {
// Get the singleton instance if one exists
// or create one if it doesn't
getInstance: function () {
if ( !instance ) {
instance = init();
}
return instance;
}
};
})();
For me the cleanest way to do so is:
const singleton = new class {
name = "foo"
constructor() {
console.log(`Singleton ${this.name} constructed`)
}
}
With this syntax you are certain your singleton is and will remain unique. You can also enjoy the sugarness of class syntax and use this as expected.
(Note that class fields require node v12+ or a modern browser.)
This is how I implement singleton pattern using ES6 features. Yes, I know this does not look like an Object-oriented approach, but I find this method is easy to implement and a clean way to implement.
const Singleton = (() => {
var _instance = !_instance && new Object('Object created....');
return () => _instance;
})();
//************************************************************************
var instance1 = Singleton();
var instance2 = Singleton();
console.log(instance1 === instance2); // true
This should work:
function Klass() {
var instance = this;
Klass = function () { return instance; }
}
I believe this is the simplest/cleanest and most intuitive way though it requires ECMAScript 2016 (ES7):
export default class Singleton {
static instance;
constructor(){
if(instance){
return instance;
}
this.state = "duke";
this.instance = this;
}
}
The source code is from: adam-bien.com
I've found the following to be the easiest singleton pattern, because using the new operator makes this immediately available within the function, eliminating the need to return an object literal:
var singleton = new (function () {
var private = "A private value";
this.printSomething = function() {
console.log(private);
}
})();
singleton.printSomething();
Using ES6 classes and private static fields. Invoking new instances of the Singleton class will return the same instance. The instance variable is also private and can't be accessed outside the class.
class Singleton {
// # is a new Javascript feature that denotes private
static #instance;
constructor() {
if (!Singleton.#instance) {
Singleton.#instance = this
}
return Singleton.#instance
}
get() {
return Singleton.#instance;
}
}
const a = new Singleton();
const b = new Singleton();
console.log(a.get() === b.get()) // true
console.log(Singleton.instance === undefined) // true
function Once() {
return this.constructor.instance || (this.constructor.instance = this);
}
function Application(name) {
let app = Once.call(this);
app.name = name;
return app;
}
If you are into classes:
class Once {
constructor() {
return this.constructor.instance || (this.constructor.instance = this);
}
}
class Application extends Once {
constructor(name) {
super();
this.name = name;
}
}
Test:
console.log(new Once() === new Once());
let app1 = new Application('Foobar');
let app2 = new Application('Barfoo');
console.log(app1 === app2);
console.log(app1.name); // Barfoo
Following is the snippet from my walkthrough to implement a singleton pattern. This occurred to me during an interview process and I felt that I should capture this somewhere.
/*************************************************
* SINGLETON PATTERN IMPLEMENTATION *
*************************************************/
// Since there aren't any classes in JavaScript, every object
// is technically a singleton if you don't inherit from it
// or copy from it.
var single = {};
// Singleton Implementations
//
// Declaring as a global object...you are being judged!
var Logger = function() {
// global_log is/will be defined in the GLOBAL scope here
if(typeof global_log === 'undefined'){
global_log = this;
}
return global_log;
};
// The below 'fix' solves the GLOABL variable problem, but
// the log_instance is publicly available and thus can be
// tampered with.
function Logger() {
if(typeof Logger.log_instance === 'undefined') {
Logger.log_instance = this;
}
return Logger.log_instance;
};
// The correct way to do it to give it a closure!
function logFactory() {
var log_instance; // Private instance
var _initLog = function() { // Private init method
log_instance = 'initialized';
console.log("logger initialized!")
}
return {
getLog : function(){ // The 'privileged' method
if(typeof log_instance === 'undefined') {
_initLog();
}
return log_instance;
}
};
}
/***** TEST CODE ************************************************
// Using the Logger singleton
var logger = logFactory(); // Did I just give LogFactory a closure?
// Create an instance of the logger
var a = logger.getLog();
// Do some work
// Get another instance of the logger
var b = logger.getLog();
// Check if the two logger instances are same
console.log(a === b); // true
*******************************************************************/
The same can be found on my gist page.
My two cents: I have a constructor function (CF), for example,
var A = function(arg1){
this.arg1 = arg1
};
I need just every object created by this CF to be the same.
var X = function(){
var instance = {};
return function(){ return instance; }
}();
Test
var x1 = new X();
var x2 = new X();
console.log(x1 === x2)
Singleton:
Ensure a class has only one instance and provides a global point of access to it.
The singleton pattern limits the number of instances of a particular object to just one. This single instance is called the singleton.
defines getInstance() which returns the unique instance.
responsible for creating and managing the instance object.
The singleton object is implemented as an immediate anonymous function. The function executes immediately by wrapping it in brackets followed by two additional brackets. It is called anonymous because it doesn't have a name.
Sample Program
var Singleton = (function () {
var instance;
function createInstance() {
var object = new Object("I am the instance");
return object;
}
return {
getInstance: function () {
if (!instance) {
instance = createInstance();
}
return instance;
}
};
})();
function run() {
var instance1 = Singleton.getInstance();
var instance2 = Singleton.getInstance();
alert("Same instance? " + (instance1 === instance2));
}
run()
Here is a simple example to explain the singleton pattern in JavaScript.
var Singleton = (function() {
var instance;
var init = function() {
return {
display:function() {
alert("This is a singleton pattern demo");
}
};
};
return {
getInstance:function(){
if(!instance){
alert("Singleton check");
instance = init();
}
return instance;
}
};
})();
// In this call first display alert("Singleton check")
// and then alert("This is a singleton pattern demo");
// It means one object is created
var inst = Singleton.getInstance();
inst.display();
// In this call only display alert("This is a singleton pattern demo")
// it means second time new object is not created,
// it uses the already created object
var inst1 = Singleton.getInstance();
inst1.display();
let MySingleton = (function () {
var _instance
function init() {
if(!_instance) {
_instance = { $knew: 1 }
}
return _instance
}
let publicAPIs = {
getInstance: function() {
return init()
}
}
// this prevents customize the MySingleton, like MySingleton.x = 1
Object.freeze(publicAPIs)
// this prevents customize the MySingleton.getInstance(), like MySingleton.getInstance().x = 1
Object.freeze(publicAPIs.getInstance())
return publicAPIs
})();
I needed several singletons with:
lazy initialisation
initial parameters
And so this was what I came up with:
createSingleton ('a', 'add', [1, 2]);
console.log(a);
function createSingleton (name, construct, args) {
window[name] = {};
window[construct].apply(window[name], args);
window[construct] = null;
}
function add (a, b) {
this.a = a;
this.b = b;
this.sum = a + b;
}
args must be Array for this to work, so if you have empty variables, just pass in []
I used the window object in the function, but I could have passed in a parameter to create my own scope
name and construct parameters are only String in order for window[] to work, but with some simple typechecking, window.name and window.construct are also possible.

Create a singleton with unique instance in Javascript [duplicate]

What is the simplest/cleanest way to implement the singleton pattern in JavaScript?
I think the easiest way is to declare a simple object literal:
var myInstance = {
method1: function () {
// ...
},
method2: function () {
// ...
}
};
If you want private members on your singleton instance, you can do something like this:
var myInstance = (function() {
var privateVar = '';
function privateMethod () {
// ...
}
return { // public interface
publicMethod1: function () {
// All private members are accessible here
},
publicMethod2: function () {
}
};
})();
This has been called the module pattern, and it basically allows you to encapsulate private members on an object, by taking advantage of the use of closures.
If you want to prevent the modification of the singleton object, you can freeze it, using the ES5 Object.freeze method.
That will make the object immutable, preventing any modification to the its structure and values.
If you are using ES6, you can represent a singleton using ES Modules very easily, and you can even hold private state by declaring variables at the module scope:
// my-singleton.js
const somePrivateState = []
function privateFn () {
// ...
}
export default {
method1() {
// ...
},
method2() {
// ...
}
}
Then you can simply import the singleton object to use it:
import myInstance from './my-singleton.js'
// ...
I think the cleanest approach is something like:
var SingletonFactory = (function(){
function SingletonClass() {
//do stuff
}
var instance;
return {
getInstance: function(){
if (instance == null) {
instance = new SingletonClass();
// Hide the constructor so the returned object can't be new'd...
instance.constructor = null;
}
return instance;
}
};
})();
Afterwards, you can invoke the function as
var test = SingletonFactory.getInstance();
I'm not sure I agree with the module pattern being used as a replacement for a singleton pattern. I've often seen singletons used and abused in places where they're wholly unnecessary, and I'm sure the module pattern fills many gaps where programmers would otherwise use a singleton. However, the module pattern is not a singleton.
Module pattern:
var foo = (function () {
"use strict";
function aPrivateFunction() {}
return { aPublicFunction: function () {...}, ... };
}());
Everything initialized in the module pattern happens when Foo is declared. Additionally, the module pattern can be used to initialize a constructor, which could then be instantiated multiple times. While the module pattern is the right tool for many jobs, it's not equivalent to a singleton.
Singleton pattern:
short form
var Foo = function () {
"use strict";
if (Foo._instance) {
// This allows the constructor to be called multiple times
// and refer to the same instance. Another option is to
// throw an error.
return Foo._instance;
}
Foo._instance = this;
// Foo initialization code
};
Foo.getInstance = function () {
"use strict";
return Foo._instance || new Foo();
}
long form, using module pattern
var Foo = (function () {
"use strict";
var instance; //prevent modification of "instance" variable
function Singleton() {
if (instance) {
return instance;
}
instance = this;
//Singleton initialization code
}
// Instance accessor
Singleton.getInstance = function () {
return instance || new Singleton();
}
return Singleton;
}());
In both versions of the singleton pattern that I've provided, the constructor itself can be used as the accessor:
var a,
b;
a = new Foo(); // Constructor initialization happens here
b = new Foo();
console.log(a === b); //true
If you don't feel comfortable using the constructor this way, you can throw an error in the if (instance) statement, and stick to using the long form:
var a,
b;
a = Foo.getInstance(); // Constructor initialization happens here
b = Foo.getInstance();
console.log(a === b); // true
I should also mention that the singleton pattern fits well with the implicit constructor function pattern:
function Foo() {
if (Foo._instance) {
return Foo._instance;
}
// If the function wasn't called as a constructor,
// call it as a constructor and return the result
if (!(this instanceof Foo)) {
return new Foo();
}
Foo._instance = this;
}
var f = new Foo(); // Calls Foo as a constructor
-or-
var f = Foo(); // Also calls Foo as a constructor
In ES6 the right way to do this is:
class MyClass {
constructor() {
if (MyClass._instance) {
throw new Error("Singleton classes can't be instantiated more than once.")
}
MyClass._instance = this;
// ... Your rest of the constructor code goes after this
}
}
var instanceOne = new MyClass() // Executes succesfully
var instanceTwo = new MyClass() // Throws error
Or, if you don't want an error to be thrown on the second instance creation, you can just return the last instance, like so:
class MyClass {
constructor() {
if (MyClass._instance) {
return MyClass._instance
}
MyClass._instance = this;
// ... Your rest of the constructor code goes after this
}
}
var instanceOne = new MyClass()
var instanceTwo = new MyClass()
console.log(instanceOne === instanceTwo) // Logs "true"
In ECMAScript 2015 (ES6):
class Singleton {
constructor () {
if (!Singleton.instance) {
Singleton.instance = this
}
// Initialize object
return Singleton.instance
}
// Properties & Methods
}
const instance = new Singleton()
Object.freeze(instance)
export default instance
If you're using node.JS then you can take advantage of node.JS caching mechanism and your Singleton will be as simple as:
class Singleton {
constructor() {
this.message = 'I am an instance';
}
}
module.exports = new Singleton();
Please note that we export not the class Singleton but instance Singleton().
Node.JS will cache and reuse the same object each time it’s required.
For more details please check: Node.JS and Singleton Pattern
The following works in Node.js version 6:
class Foo {
constructor(msg) {
if (Foo.singleton) {
return Foo.singleton;
}
this.msg = msg;
Foo.singleton = this;
return Foo.singleton;
}
}
We test:
const f = new Foo('blah');
const d = new Foo('nope');
console.log(f); // => Foo { msg: 'blah' }
console.log(d); // => Foo { msg: 'blah' }
The simplest/cleanest for me means also simply to understand and no bells & whistles as are much discussed in the Java version of the discussion:
What is an efficient way to implement a singleton pattern in Java?
The answer that would fit simplest/cleanest best there from my point of view is:
Jonathan's answer to What is an efficient way to implement a singleton pattern in Java?
And it can only partly be translated to JavaScript. Some of the difference in JavaScript are:
constructors can't be private
Classes can't have declared fields
But given the latest ECMA syntax, it is possible to get close with:
Singleton pattern as a JavaScript class example
class Singleton {
constructor(field1,field2) {
this.field1=field1;
this.field2=field2;
Singleton.instance=this;
}
static getInstance() {
if (!Singleton.instance) {
Singleton.instance=new Singleton('DefaultField1','DefaultField2');
}
return Singleton.instance;
}
}
Example Usage
console.log(Singleton.getInstance().field1);
console.log(Singleton.getInstance().field2);
Example Result
DefaultField1
DefaultField2
If you want to use classes:
class Singleton {
constructor(name, age) {
this.name = name;
this.age = age;
if(this.constructor.instance)
return this.constructor.instance;
this.constructor.instance = this;
}
}
let x = new Singleton('s', 1);
let y = new Singleton('k', 2);
Output for the above will be:
console.log(x.name, x.age, y.name, y.age) // s 1 s 1
Another way of writing Singleton using function
function AnotherSingleton (name,age) {
this.name = name;
this.age = age;
if(this.constructor.instance)
return this.constructor.instance;
this.constructor.instance = this;
}
let a = new AnotherSingleton('s', 1);
let b = new AnotherSingleton('k', 2);
Output for the above will be:
console.log(a.name, a.age, b.name, b.age) // s 1 s 1
There is more than one way to skin a cat :) Depending on your taste or specific need you can apply any of the proposed solutions. I personally go for Christian C. Salvadó's first solution whenever possible (when you don't need privacy).
Since the question was about the simplest and cleanest, that's the winner. Or even:
var myInstance = {}; // Done!
This (quote from my blog)...
var SingletonClass = new function() {
this.myFunction() {
// Do stuff
}
this.instance = 1;
}
doesn't make much sense (my blog example doesn't either) because it doesn't need any private variables, so it's pretty much the same as:
var SingletonClass = {
myFunction: function () {
// Do stuff
},
instance: 1
}
I deprecate my answer, see my other one.
Usually the module pattern (see Christian C. Salvadó's answer) which is not the singleton pattern is good enough. However, one of the features of the singleton is that its initialization is delayed till the object is needed. The module pattern lacks this feature.
My proposition (CoffeeScript):
window.singleton = (initializer) ->
instance = undefined
() ->
return instance unless instance is undefined
instance = initializer()
Which compiled to this in JavaScript:
window.singleton = function(initializer) {
var instance;
instance = void 0;
return function() {
if (instance !== void 0) {
return instance;
}
return instance = initializer();
};
};
Then I can do following:
window.iAmSingleton = singleton(function() {
/* This function should create and initialize singleton. */
alert("creating");
return {property1: 'value1', property2: 'value2'};
});
alert(window.iAmSingleton().property2); // "creating" will pop up; then "value2" will pop up
alert(window.iAmSingleton().property2); // "value2" will pop up but "creating" will not
window.iAmSingleton().property2 = 'new value';
alert(window.iAmSingleton().property2); // "new value" will pop up
I got this example from the *JavaScript Patterns
Build Better Applications with Coding and Design Patterns book (by Stoyan Stefanov). In case you need some simple implementation class like a singleton object, you can use an immediate function as in the following:
var ClassName;
(function() {
var instance;
ClassName = function ClassName() {
// If the private instance variable is already initialized, return a reference
if(instance) {
return instance;
}
// If the instance is not created, save a pointer of the original reference
// to the private instance variable.
instance = this;
// All constructor initialization will be here
// i.e.:
this.someProperty = 0;
this.someMethod = function() {
// Some action here
};
};
}());
And you can check this example by following test case:
// Extending defined class like singleton object using the new prototype property
ClassName.prototype.nothing = true;
var obj_1 = new ClassName();
// Extending the defined class like a singleton object using the new prototype property
ClassName.prototype.everything = true;
var obj_2 = new ClassName();
// Testing makes these two objects point to the same instance
console.log(obj_1 === obj_2); // Result is true, and it points to the same instance object
// All prototype properties work
// no matter when they were defined
console.log(obj_1.nothing && obj_1.everything
&& obj_2.nothing && obj_2.everything); // Result true
// Values of properties which are defined inside of the constructor
console.log(obj_1.someProperty); // Outputs 0
console.log(obj_2.someProperty); // Outputs 0
// Changing property value
obj_1.someProperty = 1;
console.log(obj_1.someProperty); // Output 1
console.log(obj_2.someProperty); // Output 1
console.log(obj_1.constructor === ClassName); // Output true
This approach passes all test cases while a private static implementation will fail when a prototype extension is used (it can be fixed, but it will not be simple) and a public static implementation less advisable due to an instance is exposed to the public.
jsFiddly demo.
Short answer:
Because of the non-blocking nature of JavaScript, singletons in JavaScript are really ugly in use. Global variables will give you one instance through the whole application too without all these callbacks, and module pattern gently hides internals behind the interface. See Christian C. Salvadó's answer.
But, since you wanted a singleton…
var singleton = function(initializer) {
var state = 'initial';
var instance;
var queue = [];
var instanceReady = function(createdInstance) {
state = 'ready';
instance = createdInstance;
while (callback = queue.shift()) {
callback(instance);
}
};
return function(callback) {
if (state === 'initial') {
state = 'waiting';
queue.push(callback);
initializer(instanceReady);
} else if (state === 'waiting') {
queue.push(callback);
} else {
callback(instance);
}
};
};
Usage:
var singletonInitializer = function(instanceReady) {
var preparedObject = {property: 'value'};
// Calling instanceReady notifies the singleton that the instance is ready to use
instanceReady(preparedObject);
}
var s = singleton(singletonInitializer);
// Get the instance and use it
s(function(instance) {
instance.doSomething();
});
Explanation:
Singletons give you more than just one instance through the whole application: their initialization is delayed till the first use. This is really a big thing when you deal with objects whose initialization is expensive. Expensive usually means I/O and in JavaScript I/O always mean callbacks.
Don't trust answers which give you interface like instance = singleton.getInstance(), they all miss the point.
If they don't take a callback to be run when an instance is ready, then they won't work when the initializer does I/O.
Yeah, callbacks always look uglier than a function call which immediately returns an object instance. But again: when you do I/O, callbacks are obligatory. If you don't want to do any I/O, then instantiation is cheap enough to do it at program start.
Example 1, cheap initializer:
var simpleInitializer = function(instanceReady) {
console.log("Initializer started");
instanceReady({property: "initial value"});
}
var simple = singleton(simpleInitializer);
console.log("Tests started. Singleton instance should not be initalized yet.");
simple(function(inst) {
console.log("Access 1");
console.log("Current property value: " + inst.property);
console.log("Let's reassign this property");
inst.property = "new value";
});
simple(function(inst) {
console.log("Access 2");
console.log("Current property value: " + inst.property);
});
Example 2, initialization with I/O:
In this example, setTimeout fakes some expensive I/O operation. This illustrates why singletons in JavaScript really need callbacks.
var heavyInitializer = function(instanceReady) {
console.log("Initializer started");
var onTimeout = function() {
console.log("Initializer did his heavy work");
instanceReady({property: "initial value"});
};
setTimeout(onTimeout, 500);
};
var heavy = singleton(heavyInitializer);
console.log("In this example we will be trying");
console.log("to access singleton twice before it finishes initialization.");
heavy(function(inst) {
console.log("Access 1");
console.log("Current property value: " + inst.property);
console.log("Let's reassign this property");
inst.property = "new value";
});
heavy(function(inst) {
console.log("Access 2. You can see callbacks order is preserved.");
console.log("Current property value: " + inst.property);
});
console.log("We made it to the end of the file. Instance is not ready yet.");
Christian C. Salvadó's and zzzzBov's answer have both given wonderful answers, but just to add my own interpretation based on my having moved into heavy Node.js development from PHP/Zend Framework where singleton patterns were common.
The following, comment-documented code is based on the following requirements:
one and only one instance of the function object may be instantiated
the instance is not publicly available and may only be accessed through a public method
the constructor is not publicly available and may only be instantiated if there is not already an instance available
the declaration of the constructor must allow its prototype chain to be modified. This will allow the constructor to inherit from other prototypes, and offer "public" methods for the instance
My code is very similar to zzzzBov's answer except I've added a prototype chain to the constructor and more comments that should help those coming from PHP or a similar language translate traditional OOP to JavaScript's prototypical nature. It may not be the "simplest" but I believe it is the most proper.
// Declare 'Singleton' as the returned value of a self-executing anonymous function
var Singleton = (function () {
"use strict";
// 'instance' and 'constructor' should not be available in a "public" scope
// here they are "private", thus available only within
// the scope of the self-executing anonymous function
var _instance=null;
var _constructor = function (name) {
this.name = name || 'default';
}
// Prototypes will be "public" methods available from the instance
_constructor.prototype.getName = function () {
return this.name;
}
// Using the module pattern, return a static object
// which essentially is a list of "public static" methods
return {
// Because getInstance is defined within the same scope
// it can access the "private" 'instance' and 'constructor' vars
getInstance:function (name) {
if (!_instance) {
console.log('creating'); // This should only happen once
_instance = new _constructor(name);
}
console.log('returning');
return _instance;
}
}
})(); // Self execute
// Ensure 'instance' and 'constructor' are unavailable
// outside the scope in which they were defined
// thus making them "private" and not "public"
console.log(typeof _instance); // undefined
console.log(typeof _constructor); // undefined
// Assign instance to two different variables
var a = Singleton.getInstance('first');
var b = Singleton.getInstance('second'); // passing a name here does nothing because the single instance was already instantiated
// Ensure 'a' and 'b' are truly equal
console.log(a === b); // true
console.log(a.getName()); // "first"
console.log(b.getName()); // Also returns "first" because it's the same instance as 'a'
Note that technically, the self-executing anonymous function is itself a singleton as demonstrated nicely in the code provided by Christian C. Salvadó. The only catch here is that it is not possible to modify the prototype chain of the constructor when the constructor itself is anonymous.
Keep in mind that to JavaScript, the concepts of “public” and “private” do not apply as they do in PHP or Java. But we have achieved the same effect by leveraging JavaScript’s rules of functional scope availability.
You could just do:
var singleton = new (function() {
var bar = 123
this.foo = function() {
// Whatever
}
})()
I think I have found the cleanest way to program in JavaScript, but you'll need some imagination. I got this idea from a working technique in the book JavaScript: The Good Parts.
Instead of using the new keyword, you could create a class like this:
function Class()
{
var obj = {}; // Could also be used for inheritance if you don't start with an empty object.
var privateVar;
obj.publicVar;
obj.publicMethod = publicMethod;
function publicMethod(){}
function privateMethod(){}
return obj;
}
You can instantiate the above object by saying:
var objInst = Class(); // !!! NO NEW KEYWORD
Now with this work method in mind, you could create a singleton like this:
ClassSingleton = function()
{
var instance = null;
function Class() // This is the class like the above one
{
var obj = {};
return obj;
}
function getInstance()
{
if( !instance )
instance = Class(); // Again no 'new' keyword;
return instance;
}
return { getInstance : getInstance };
}();
Now you can get your instance by calling
var obj = ClassSingleton.getInstance();
I think this is the neatest way as the complete "Class" is not even accessible.
The clearest answer should be this one from the book Learning JavaScript Design Patterns by Addy Osmani.
var mySingleton = (function () {
// Instance stores a reference to the singleton
var instance;
function init() {
// Singleton
// Private methods and variables
function privateMethod(){
console.log( "I am private" );
}
var privateVariable = "I'm also private";
var privateRandomNumber = Math.random();
return {
// Public methods and variables
publicMethod: function () {
console.log( "The public can see me!" );
},
publicProperty: "I am also public",
getRandomNumber: function() {
return privateRandomNumber;
}
};
};
return {
// Get the singleton instance if one exists
// or create one if it doesn't
getInstance: function () {
if ( !instance ) {
instance = init();
}
return instance;
}
};
})();
For me the cleanest way to do so is:
const singleton = new class {
name = "foo"
constructor() {
console.log(`Singleton ${this.name} constructed`)
}
}
With this syntax you are certain your singleton is and will remain unique. You can also enjoy the sugarness of class syntax and use this as expected.
(Note that class fields require node v12+ or a modern browser.)
This is how I implement singleton pattern using ES6 features. Yes, I know this does not look like an Object-oriented approach, but I find this method is easy to implement and a clean way to implement.
const Singleton = (() => {
var _instance = !_instance && new Object('Object created....');
return () => _instance;
})();
//************************************************************************
var instance1 = Singleton();
var instance2 = Singleton();
console.log(instance1 === instance2); // true
This should work:
function Klass() {
var instance = this;
Klass = function () { return instance; }
}
I believe this is the simplest/cleanest and most intuitive way though it requires ECMAScript 2016 (ES7):
export default class Singleton {
static instance;
constructor(){
if(instance){
return instance;
}
this.state = "duke";
this.instance = this;
}
}
The source code is from: adam-bien.com
I've found the following to be the easiest singleton pattern, because using the new operator makes this immediately available within the function, eliminating the need to return an object literal:
var singleton = new (function () {
var private = "A private value";
this.printSomething = function() {
console.log(private);
}
})();
singleton.printSomething();
Using ES6 classes and private static fields. Invoking new instances of the Singleton class will return the same instance. The instance variable is also private and can't be accessed outside the class.
class Singleton {
// # is a new Javascript feature that denotes private
static #instance;
constructor() {
if (!Singleton.#instance) {
Singleton.#instance = this
}
return Singleton.#instance
}
get() {
return Singleton.#instance;
}
}
const a = new Singleton();
const b = new Singleton();
console.log(a.get() === b.get()) // true
console.log(Singleton.instance === undefined) // true
function Once() {
return this.constructor.instance || (this.constructor.instance = this);
}
function Application(name) {
let app = Once.call(this);
app.name = name;
return app;
}
If you are into classes:
class Once {
constructor() {
return this.constructor.instance || (this.constructor.instance = this);
}
}
class Application extends Once {
constructor(name) {
super();
this.name = name;
}
}
Test:
console.log(new Once() === new Once());
let app1 = new Application('Foobar');
let app2 = new Application('Barfoo');
console.log(app1 === app2);
console.log(app1.name); // Barfoo
Following is the snippet from my walkthrough to implement a singleton pattern. This occurred to me during an interview process and I felt that I should capture this somewhere.
/*************************************************
* SINGLETON PATTERN IMPLEMENTATION *
*************************************************/
// Since there aren't any classes in JavaScript, every object
// is technically a singleton if you don't inherit from it
// or copy from it.
var single = {};
// Singleton Implementations
//
// Declaring as a global object...you are being judged!
var Logger = function() {
// global_log is/will be defined in the GLOBAL scope here
if(typeof global_log === 'undefined'){
global_log = this;
}
return global_log;
};
// The below 'fix' solves the GLOABL variable problem, but
// the log_instance is publicly available and thus can be
// tampered with.
function Logger() {
if(typeof Logger.log_instance === 'undefined') {
Logger.log_instance = this;
}
return Logger.log_instance;
};
// The correct way to do it to give it a closure!
function logFactory() {
var log_instance; // Private instance
var _initLog = function() { // Private init method
log_instance = 'initialized';
console.log("logger initialized!")
}
return {
getLog : function(){ // The 'privileged' method
if(typeof log_instance === 'undefined') {
_initLog();
}
return log_instance;
}
};
}
/***** TEST CODE ************************************************
// Using the Logger singleton
var logger = logFactory(); // Did I just give LogFactory a closure?
// Create an instance of the logger
var a = logger.getLog();
// Do some work
// Get another instance of the logger
var b = logger.getLog();
// Check if the two logger instances are same
console.log(a === b); // true
*******************************************************************/
The same can be found on my gist page.
My two cents: I have a constructor function (CF), for example,
var A = function(arg1){
this.arg1 = arg1
};
I need just every object created by this CF to be the same.
var X = function(){
var instance = {};
return function(){ return instance; }
}();
Test
var x1 = new X();
var x2 = new X();
console.log(x1 === x2)
Singleton:
Ensure a class has only one instance and provides a global point of access to it.
The singleton pattern limits the number of instances of a particular object to just one. This single instance is called the singleton.
defines getInstance() which returns the unique instance.
responsible for creating and managing the instance object.
The singleton object is implemented as an immediate anonymous function. The function executes immediately by wrapping it in brackets followed by two additional brackets. It is called anonymous because it doesn't have a name.
Sample Program
var Singleton = (function () {
var instance;
function createInstance() {
var object = new Object("I am the instance");
return object;
}
return {
getInstance: function () {
if (!instance) {
instance = createInstance();
}
return instance;
}
};
})();
function run() {
var instance1 = Singleton.getInstance();
var instance2 = Singleton.getInstance();
alert("Same instance? " + (instance1 === instance2));
}
run()
Here is a simple example to explain the singleton pattern in JavaScript.
var Singleton = (function() {
var instance;
var init = function() {
return {
display:function() {
alert("This is a singleton pattern demo");
}
};
};
return {
getInstance:function(){
if(!instance){
alert("Singleton check");
instance = init();
}
return instance;
}
};
})();
// In this call first display alert("Singleton check")
// and then alert("This is a singleton pattern demo");
// It means one object is created
var inst = Singleton.getInstance();
inst.display();
// In this call only display alert("This is a singleton pattern demo")
// it means second time new object is not created,
// it uses the already created object
var inst1 = Singleton.getInstance();
inst1.display();
let MySingleton = (function () {
var _instance
function init() {
if(!_instance) {
_instance = { $knew: 1 }
}
return _instance
}
let publicAPIs = {
getInstance: function() {
return init()
}
}
// this prevents customize the MySingleton, like MySingleton.x = 1
Object.freeze(publicAPIs)
// this prevents customize the MySingleton.getInstance(), like MySingleton.getInstance().x = 1
Object.freeze(publicAPIs.getInstance())
return publicAPIs
})();
I needed several singletons with:
lazy initialisation
initial parameters
And so this was what I came up with:
createSingleton ('a', 'add', [1, 2]);
console.log(a);
function createSingleton (name, construct, args) {
window[name] = {};
window[construct].apply(window[name], args);
window[construct] = null;
}
function add (a, b) {
this.a = a;
this.b = b;
this.sum = a + b;
}
args must be Array for this to work, so if you have empty variables, just pass in []
I used the window object in the function, but I could have passed in a parameter to create my own scope
name and construct parameters are only String in order for window[] to work, but with some simple typechecking, window.name and window.construct are also possible.

How to create singleton class and where we should use singleton class in Javascript? [duplicate]

What is the simplest/cleanest way to implement the singleton pattern in JavaScript?
I think the easiest way is to declare a simple object literal:
var myInstance = {
method1: function () {
// ...
},
method2: function () {
// ...
}
};
If you want private members on your singleton instance, you can do something like this:
var myInstance = (function() {
var privateVar = '';
function privateMethod () {
// ...
}
return { // public interface
publicMethod1: function () {
// All private members are accessible here
},
publicMethod2: function () {
}
};
})();
This has been called the module pattern, and it basically allows you to encapsulate private members on an object, by taking advantage of the use of closures.
If you want to prevent the modification of the singleton object, you can freeze it, using the ES5 Object.freeze method.
That will make the object immutable, preventing any modification to the its structure and values.
If you are using ES6, you can represent a singleton using ES Modules very easily, and you can even hold private state by declaring variables at the module scope:
// my-singleton.js
const somePrivateState = []
function privateFn () {
// ...
}
export default {
method1() {
// ...
},
method2() {
// ...
}
}
Then you can simply import the singleton object to use it:
import myInstance from './my-singleton.js'
// ...
I think the cleanest approach is something like:
var SingletonFactory = (function(){
function SingletonClass() {
//do stuff
}
var instance;
return {
getInstance: function(){
if (instance == null) {
instance = new SingletonClass();
// Hide the constructor so the returned object can't be new'd...
instance.constructor = null;
}
return instance;
}
};
})();
Afterwards, you can invoke the function as
var test = SingletonFactory.getInstance();
I'm not sure I agree with the module pattern being used as a replacement for a singleton pattern. I've often seen singletons used and abused in places where they're wholly unnecessary, and I'm sure the module pattern fills many gaps where programmers would otherwise use a singleton. However, the module pattern is not a singleton.
Module pattern:
var foo = (function () {
"use strict";
function aPrivateFunction() {}
return { aPublicFunction: function () {...}, ... };
}());
Everything initialized in the module pattern happens when Foo is declared. Additionally, the module pattern can be used to initialize a constructor, which could then be instantiated multiple times. While the module pattern is the right tool for many jobs, it's not equivalent to a singleton.
Singleton pattern:
short form
var Foo = function () {
"use strict";
if (Foo._instance) {
// This allows the constructor to be called multiple times
// and refer to the same instance. Another option is to
// throw an error.
return Foo._instance;
}
Foo._instance = this;
// Foo initialization code
};
Foo.getInstance = function () {
"use strict";
return Foo._instance || new Foo();
}
long form, using module pattern
var Foo = (function () {
"use strict";
var instance; //prevent modification of "instance" variable
function Singleton() {
if (instance) {
return instance;
}
instance = this;
//Singleton initialization code
}
// Instance accessor
Singleton.getInstance = function () {
return instance || new Singleton();
}
return Singleton;
}());
In both versions of the singleton pattern that I've provided, the constructor itself can be used as the accessor:
var a,
b;
a = new Foo(); // Constructor initialization happens here
b = new Foo();
console.log(a === b); //true
If you don't feel comfortable using the constructor this way, you can throw an error in the if (instance) statement, and stick to using the long form:
var a,
b;
a = Foo.getInstance(); // Constructor initialization happens here
b = Foo.getInstance();
console.log(a === b); // true
I should also mention that the singleton pattern fits well with the implicit constructor function pattern:
function Foo() {
if (Foo._instance) {
return Foo._instance;
}
// If the function wasn't called as a constructor,
// call it as a constructor and return the result
if (!(this instanceof Foo)) {
return new Foo();
}
Foo._instance = this;
}
var f = new Foo(); // Calls Foo as a constructor
-or-
var f = Foo(); // Also calls Foo as a constructor
In ES6 the right way to do this is:
class MyClass {
constructor() {
if (MyClass._instance) {
throw new Error("Singleton classes can't be instantiated more than once.")
}
MyClass._instance = this;
// ... Your rest of the constructor code goes after this
}
}
var instanceOne = new MyClass() // Executes succesfully
var instanceTwo = new MyClass() // Throws error
Or, if you don't want an error to be thrown on the second instance creation, you can just return the last instance, like so:
class MyClass {
constructor() {
if (MyClass._instance) {
return MyClass._instance
}
MyClass._instance = this;
// ... Your rest of the constructor code goes after this
}
}
var instanceOne = new MyClass()
var instanceTwo = new MyClass()
console.log(instanceOne === instanceTwo) // Logs "true"
In ECMAScript 2015 (ES6):
class Singleton {
constructor () {
if (!Singleton.instance) {
Singleton.instance = this
}
// Initialize object
return Singleton.instance
}
// Properties & Methods
}
const instance = new Singleton()
Object.freeze(instance)
export default instance
If you're using node.JS then you can take advantage of node.JS caching mechanism and your Singleton will be as simple as:
class Singleton {
constructor() {
this.message = 'I am an instance';
}
}
module.exports = new Singleton();
Please note that we export not the class Singleton but instance Singleton().
Node.JS will cache and reuse the same object each time it’s required.
For more details please check: Node.JS and Singleton Pattern
The following works in Node.js version 6:
class Foo {
constructor(msg) {
if (Foo.singleton) {
return Foo.singleton;
}
this.msg = msg;
Foo.singleton = this;
return Foo.singleton;
}
}
We test:
const f = new Foo('blah');
const d = new Foo('nope');
console.log(f); // => Foo { msg: 'blah' }
console.log(d); // => Foo { msg: 'blah' }
The simplest/cleanest for me means also simply to understand and no bells & whistles as are much discussed in the Java version of the discussion:
What is an efficient way to implement a singleton pattern in Java?
The answer that would fit simplest/cleanest best there from my point of view is:
Jonathan's answer to What is an efficient way to implement a singleton pattern in Java?
And it can only partly be translated to JavaScript. Some of the difference in JavaScript are:
constructors can't be private
Classes can't have declared fields
But given the latest ECMA syntax, it is possible to get close with:
Singleton pattern as a JavaScript class example
class Singleton {
constructor(field1,field2) {
this.field1=field1;
this.field2=field2;
Singleton.instance=this;
}
static getInstance() {
if (!Singleton.instance) {
Singleton.instance=new Singleton('DefaultField1','DefaultField2');
}
return Singleton.instance;
}
}
Example Usage
console.log(Singleton.getInstance().field1);
console.log(Singleton.getInstance().field2);
Example Result
DefaultField1
DefaultField2
If you want to use classes:
class Singleton {
constructor(name, age) {
this.name = name;
this.age = age;
if(this.constructor.instance)
return this.constructor.instance;
this.constructor.instance = this;
}
}
let x = new Singleton('s', 1);
let y = new Singleton('k', 2);
Output for the above will be:
console.log(x.name, x.age, y.name, y.age) // s 1 s 1
Another way of writing Singleton using function
function AnotherSingleton (name,age) {
this.name = name;
this.age = age;
if(this.constructor.instance)
return this.constructor.instance;
this.constructor.instance = this;
}
let a = new AnotherSingleton('s', 1);
let b = new AnotherSingleton('k', 2);
Output for the above will be:
console.log(a.name, a.age, b.name, b.age) // s 1 s 1
There is more than one way to skin a cat :) Depending on your taste or specific need you can apply any of the proposed solutions. I personally go for Christian C. Salvadó's first solution whenever possible (when you don't need privacy).
Since the question was about the simplest and cleanest, that's the winner. Or even:
var myInstance = {}; // Done!
This (quote from my blog)...
var SingletonClass = new function() {
this.myFunction() {
// Do stuff
}
this.instance = 1;
}
doesn't make much sense (my blog example doesn't either) because it doesn't need any private variables, so it's pretty much the same as:
var SingletonClass = {
myFunction: function () {
// Do stuff
},
instance: 1
}
I deprecate my answer, see my other one.
Usually the module pattern (see Christian C. Salvadó's answer) which is not the singleton pattern is good enough. However, one of the features of the singleton is that its initialization is delayed till the object is needed. The module pattern lacks this feature.
My proposition (CoffeeScript):
window.singleton = (initializer) ->
instance = undefined
() ->
return instance unless instance is undefined
instance = initializer()
Which compiled to this in JavaScript:
window.singleton = function(initializer) {
var instance;
instance = void 0;
return function() {
if (instance !== void 0) {
return instance;
}
return instance = initializer();
};
};
Then I can do following:
window.iAmSingleton = singleton(function() {
/* This function should create and initialize singleton. */
alert("creating");
return {property1: 'value1', property2: 'value2'};
});
alert(window.iAmSingleton().property2); // "creating" will pop up; then "value2" will pop up
alert(window.iAmSingleton().property2); // "value2" will pop up but "creating" will not
window.iAmSingleton().property2 = 'new value';
alert(window.iAmSingleton().property2); // "new value" will pop up
I got this example from the *JavaScript Patterns
Build Better Applications with Coding and Design Patterns book (by Stoyan Stefanov). In case you need some simple implementation class like a singleton object, you can use an immediate function as in the following:
var ClassName;
(function() {
var instance;
ClassName = function ClassName() {
// If the private instance variable is already initialized, return a reference
if(instance) {
return instance;
}
// If the instance is not created, save a pointer of the original reference
// to the private instance variable.
instance = this;
// All constructor initialization will be here
// i.e.:
this.someProperty = 0;
this.someMethod = function() {
// Some action here
};
};
}());
And you can check this example by following test case:
// Extending defined class like singleton object using the new prototype property
ClassName.prototype.nothing = true;
var obj_1 = new ClassName();
// Extending the defined class like a singleton object using the new prototype property
ClassName.prototype.everything = true;
var obj_2 = new ClassName();
// Testing makes these two objects point to the same instance
console.log(obj_1 === obj_2); // Result is true, and it points to the same instance object
// All prototype properties work
// no matter when they were defined
console.log(obj_1.nothing && obj_1.everything
&& obj_2.nothing && obj_2.everything); // Result true
// Values of properties which are defined inside of the constructor
console.log(obj_1.someProperty); // Outputs 0
console.log(obj_2.someProperty); // Outputs 0
// Changing property value
obj_1.someProperty = 1;
console.log(obj_1.someProperty); // Output 1
console.log(obj_2.someProperty); // Output 1
console.log(obj_1.constructor === ClassName); // Output true
This approach passes all test cases while a private static implementation will fail when a prototype extension is used (it can be fixed, but it will not be simple) and a public static implementation less advisable due to an instance is exposed to the public.
jsFiddly demo.
Short answer:
Because of the non-blocking nature of JavaScript, singletons in JavaScript are really ugly in use. Global variables will give you one instance through the whole application too without all these callbacks, and module pattern gently hides internals behind the interface. See Christian C. Salvadó's answer.
But, since you wanted a singleton…
var singleton = function(initializer) {
var state = 'initial';
var instance;
var queue = [];
var instanceReady = function(createdInstance) {
state = 'ready';
instance = createdInstance;
while (callback = queue.shift()) {
callback(instance);
}
};
return function(callback) {
if (state === 'initial') {
state = 'waiting';
queue.push(callback);
initializer(instanceReady);
} else if (state === 'waiting') {
queue.push(callback);
} else {
callback(instance);
}
};
};
Usage:
var singletonInitializer = function(instanceReady) {
var preparedObject = {property: 'value'};
// Calling instanceReady notifies the singleton that the instance is ready to use
instanceReady(preparedObject);
}
var s = singleton(singletonInitializer);
// Get the instance and use it
s(function(instance) {
instance.doSomething();
});
Explanation:
Singletons give you more than just one instance through the whole application: their initialization is delayed till the first use. This is really a big thing when you deal with objects whose initialization is expensive. Expensive usually means I/O and in JavaScript I/O always mean callbacks.
Don't trust answers which give you interface like instance = singleton.getInstance(), they all miss the point.
If they don't take a callback to be run when an instance is ready, then they won't work when the initializer does I/O.
Yeah, callbacks always look uglier than a function call which immediately returns an object instance. But again: when you do I/O, callbacks are obligatory. If you don't want to do any I/O, then instantiation is cheap enough to do it at program start.
Example 1, cheap initializer:
var simpleInitializer = function(instanceReady) {
console.log("Initializer started");
instanceReady({property: "initial value"});
}
var simple = singleton(simpleInitializer);
console.log("Tests started. Singleton instance should not be initalized yet.");
simple(function(inst) {
console.log("Access 1");
console.log("Current property value: " + inst.property);
console.log("Let's reassign this property");
inst.property = "new value";
});
simple(function(inst) {
console.log("Access 2");
console.log("Current property value: " + inst.property);
});
Example 2, initialization with I/O:
In this example, setTimeout fakes some expensive I/O operation. This illustrates why singletons in JavaScript really need callbacks.
var heavyInitializer = function(instanceReady) {
console.log("Initializer started");
var onTimeout = function() {
console.log("Initializer did his heavy work");
instanceReady({property: "initial value"});
};
setTimeout(onTimeout, 500);
};
var heavy = singleton(heavyInitializer);
console.log("In this example we will be trying");
console.log("to access singleton twice before it finishes initialization.");
heavy(function(inst) {
console.log("Access 1");
console.log("Current property value: " + inst.property);
console.log("Let's reassign this property");
inst.property = "new value";
});
heavy(function(inst) {
console.log("Access 2. You can see callbacks order is preserved.");
console.log("Current property value: " + inst.property);
});
console.log("We made it to the end of the file. Instance is not ready yet.");
Christian C. Salvadó's and zzzzBov's answer have both given wonderful answers, but just to add my own interpretation based on my having moved into heavy Node.js development from PHP/Zend Framework where singleton patterns were common.
The following, comment-documented code is based on the following requirements:
one and only one instance of the function object may be instantiated
the instance is not publicly available and may only be accessed through a public method
the constructor is not publicly available and may only be instantiated if there is not already an instance available
the declaration of the constructor must allow its prototype chain to be modified. This will allow the constructor to inherit from other prototypes, and offer "public" methods for the instance
My code is very similar to zzzzBov's answer except I've added a prototype chain to the constructor and more comments that should help those coming from PHP or a similar language translate traditional OOP to JavaScript's prototypical nature. It may not be the "simplest" but I believe it is the most proper.
// Declare 'Singleton' as the returned value of a self-executing anonymous function
var Singleton = (function () {
"use strict";
// 'instance' and 'constructor' should not be available in a "public" scope
// here they are "private", thus available only within
// the scope of the self-executing anonymous function
var _instance=null;
var _constructor = function (name) {
this.name = name || 'default';
}
// Prototypes will be "public" methods available from the instance
_constructor.prototype.getName = function () {
return this.name;
}
// Using the module pattern, return a static object
// which essentially is a list of "public static" methods
return {
// Because getInstance is defined within the same scope
// it can access the "private" 'instance' and 'constructor' vars
getInstance:function (name) {
if (!_instance) {
console.log('creating'); // This should only happen once
_instance = new _constructor(name);
}
console.log('returning');
return _instance;
}
}
})(); // Self execute
// Ensure 'instance' and 'constructor' are unavailable
// outside the scope in which they were defined
// thus making them "private" and not "public"
console.log(typeof _instance); // undefined
console.log(typeof _constructor); // undefined
// Assign instance to two different variables
var a = Singleton.getInstance('first');
var b = Singleton.getInstance('second'); // passing a name here does nothing because the single instance was already instantiated
// Ensure 'a' and 'b' are truly equal
console.log(a === b); // true
console.log(a.getName()); // "first"
console.log(b.getName()); // Also returns "first" because it's the same instance as 'a'
Note that technically, the self-executing anonymous function is itself a singleton as demonstrated nicely in the code provided by Christian C. Salvadó. The only catch here is that it is not possible to modify the prototype chain of the constructor when the constructor itself is anonymous.
Keep in mind that to JavaScript, the concepts of “public” and “private” do not apply as they do in PHP or Java. But we have achieved the same effect by leveraging JavaScript’s rules of functional scope availability.
You could just do:
var singleton = new (function() {
var bar = 123
this.foo = function() {
// Whatever
}
})()
I think I have found the cleanest way to program in JavaScript, but you'll need some imagination. I got this idea from a working technique in the book JavaScript: The Good Parts.
Instead of using the new keyword, you could create a class like this:
function Class()
{
var obj = {}; // Could also be used for inheritance if you don't start with an empty object.
var privateVar;
obj.publicVar;
obj.publicMethod = publicMethod;
function publicMethod(){}
function privateMethod(){}
return obj;
}
You can instantiate the above object by saying:
var objInst = Class(); // !!! NO NEW KEYWORD
Now with this work method in mind, you could create a singleton like this:
ClassSingleton = function()
{
var instance = null;
function Class() // This is the class like the above one
{
var obj = {};
return obj;
}
function getInstance()
{
if( !instance )
instance = Class(); // Again no 'new' keyword;
return instance;
}
return { getInstance : getInstance };
}();
Now you can get your instance by calling
var obj = ClassSingleton.getInstance();
I think this is the neatest way as the complete "Class" is not even accessible.
The clearest answer should be this one from the book Learning JavaScript Design Patterns by Addy Osmani.
var mySingleton = (function () {
// Instance stores a reference to the singleton
var instance;
function init() {
// Singleton
// Private methods and variables
function privateMethod(){
console.log( "I am private" );
}
var privateVariable = "I'm also private";
var privateRandomNumber = Math.random();
return {
// Public methods and variables
publicMethod: function () {
console.log( "The public can see me!" );
},
publicProperty: "I am also public",
getRandomNumber: function() {
return privateRandomNumber;
}
};
};
return {
// Get the singleton instance if one exists
// or create one if it doesn't
getInstance: function () {
if ( !instance ) {
instance = init();
}
return instance;
}
};
})();
For me the cleanest way to do so is:
const singleton = new class {
name = "foo"
constructor() {
console.log(`Singleton ${this.name} constructed`)
}
}
With this syntax you are certain your singleton is and will remain unique. You can also enjoy the sugarness of class syntax and use this as expected.
(Note that class fields require node v12+ or a modern browser.)
This is how I implement singleton pattern using ES6 features. Yes, I know this does not look like an Object-oriented approach, but I find this method is easy to implement and a clean way to implement.
const Singleton = (() => {
var _instance = !_instance && new Object('Object created....');
return () => _instance;
})();
//************************************************************************
var instance1 = Singleton();
var instance2 = Singleton();
console.log(instance1 === instance2); // true
This should work:
function Klass() {
var instance = this;
Klass = function () { return instance; }
}
I believe this is the simplest/cleanest and most intuitive way though it requires ECMAScript 2016 (ES7):
export default class Singleton {
static instance;
constructor(){
if(instance){
return instance;
}
this.state = "duke";
this.instance = this;
}
}
The source code is from: adam-bien.com
I've found the following to be the easiest singleton pattern, because using the new operator makes this immediately available within the function, eliminating the need to return an object literal:
var singleton = new (function () {
var private = "A private value";
this.printSomething = function() {
console.log(private);
}
})();
singleton.printSomething();
Using ES6 classes and private static fields. Invoking new instances of the Singleton class will return the same instance. The instance variable is also private and can't be accessed outside the class.
class Singleton {
// # is a new Javascript feature that denotes private
static #instance;
constructor() {
if (!Singleton.#instance) {
Singleton.#instance = this
}
return Singleton.#instance
}
get() {
return Singleton.#instance;
}
}
const a = new Singleton();
const b = new Singleton();
console.log(a.get() === b.get()) // true
console.log(Singleton.instance === undefined) // true
function Once() {
return this.constructor.instance || (this.constructor.instance = this);
}
function Application(name) {
let app = Once.call(this);
app.name = name;
return app;
}
If you are into classes:
class Once {
constructor() {
return this.constructor.instance || (this.constructor.instance = this);
}
}
class Application extends Once {
constructor(name) {
super();
this.name = name;
}
}
Test:
console.log(new Once() === new Once());
let app1 = new Application('Foobar');
let app2 = new Application('Barfoo');
console.log(app1 === app2);
console.log(app1.name); // Barfoo
Following is the snippet from my walkthrough to implement a singleton pattern. This occurred to me during an interview process and I felt that I should capture this somewhere.
/*************************************************
* SINGLETON PATTERN IMPLEMENTATION *
*************************************************/
// Since there aren't any classes in JavaScript, every object
// is technically a singleton if you don't inherit from it
// or copy from it.
var single = {};
// Singleton Implementations
//
// Declaring as a global object...you are being judged!
var Logger = function() {
// global_log is/will be defined in the GLOBAL scope here
if(typeof global_log === 'undefined'){
global_log = this;
}
return global_log;
};
// The below 'fix' solves the GLOABL variable problem, but
// the log_instance is publicly available and thus can be
// tampered with.
function Logger() {
if(typeof Logger.log_instance === 'undefined') {
Logger.log_instance = this;
}
return Logger.log_instance;
};
// The correct way to do it to give it a closure!
function logFactory() {
var log_instance; // Private instance
var _initLog = function() { // Private init method
log_instance = 'initialized';
console.log("logger initialized!")
}
return {
getLog : function(){ // The 'privileged' method
if(typeof log_instance === 'undefined') {
_initLog();
}
return log_instance;
}
};
}
/***** TEST CODE ************************************************
// Using the Logger singleton
var logger = logFactory(); // Did I just give LogFactory a closure?
// Create an instance of the logger
var a = logger.getLog();
// Do some work
// Get another instance of the logger
var b = logger.getLog();
// Check if the two logger instances are same
console.log(a === b); // true
*******************************************************************/
The same can be found on my gist page.
My two cents: I have a constructor function (CF), for example,
var A = function(arg1){
this.arg1 = arg1
};
I need just every object created by this CF to be the same.
var X = function(){
var instance = {};
return function(){ return instance; }
}();
Test
var x1 = new X();
var x2 = new X();
console.log(x1 === x2)
Singleton:
Ensure a class has only one instance and provides a global point of access to it.
The singleton pattern limits the number of instances of a particular object to just one. This single instance is called the singleton.
defines getInstance() which returns the unique instance.
responsible for creating and managing the instance object.
The singleton object is implemented as an immediate anonymous function. The function executes immediately by wrapping it in brackets followed by two additional brackets. It is called anonymous because it doesn't have a name.
Sample Program
var Singleton = (function () {
var instance;
function createInstance() {
var object = new Object("I am the instance");
return object;
}
return {
getInstance: function () {
if (!instance) {
instance = createInstance();
}
return instance;
}
};
})();
function run() {
var instance1 = Singleton.getInstance();
var instance2 = Singleton.getInstance();
alert("Same instance? " + (instance1 === instance2));
}
run()
Here is a simple example to explain the singleton pattern in JavaScript.
var Singleton = (function() {
var instance;
var init = function() {
return {
display:function() {
alert("This is a singleton pattern demo");
}
};
};
return {
getInstance:function(){
if(!instance){
alert("Singleton check");
instance = init();
}
return instance;
}
};
})();
// In this call first display alert("Singleton check")
// and then alert("This is a singleton pattern demo");
// It means one object is created
var inst = Singleton.getInstance();
inst.display();
// In this call only display alert("This is a singleton pattern demo")
// it means second time new object is not created,
// it uses the already created object
var inst1 = Singleton.getInstance();
inst1.display();
let MySingleton = (function () {
var _instance
function init() {
if(!_instance) {
_instance = { $knew: 1 }
}
return _instance
}
let publicAPIs = {
getInstance: function() {
return init()
}
}
// this prevents customize the MySingleton, like MySingleton.x = 1
Object.freeze(publicAPIs)
// this prevents customize the MySingleton.getInstance(), like MySingleton.getInstance().x = 1
Object.freeze(publicAPIs.getInstance())
return publicAPIs
})();
I needed several singletons with:
lazy initialisation
initial parameters
And so this was what I came up with:
createSingleton ('a', 'add', [1, 2]);
console.log(a);
function createSingleton (name, construct, args) {
window[name] = {};
window[construct].apply(window[name], args);
window[construct] = null;
}
function add (a, b) {
this.a = a;
this.b = b;
this.sum = a + b;
}
args must be Array for this to work, so if you have empty variables, just pass in []
I used the window object in the function, but I could have passed in a parameter to create my own scope
name and construct parameters are only String in order for window[] to work, but with some simple typechecking, window.name and window.construct are also possible.

Defining an interface in JavaScript via prototype chain

I know that in several languages like C++, you can create classes with multiple inheritance (or at least simulate it using interfaces like in Java). In JavaScript, is it possible to define an interface that can be implemented on a class? If so, what would be the best way to approach doing this, ideally incorporating the prototype chain somehow. Would below work, or is there a better way?
function Gizmo() {
console.log('Gizmo constructed');
}
Gizmo.prototype.wamboozle = function () {
console.log('wamboozle');
};
function EventEmitter() {
console.log('EventEmitter constructed');
this.events = {};
}
EventEmitter.prototype.on = function (name, callback) {
this.events[name] ? this.events[name].push(callback) : (this.events[name] = [callback]);
};
EventEmitter.prototype.emit = function (name, event) {
if (this.events[name]) {
this.events[name].forEach(function (callback) {
callback(event);
});
}
};
// set up inheritance and implementation
// maybe this could be a possibility?
Doohickey.prototype = Object.create(Gizmo.prototype);
Object.getOwnPropertyNames(EventEmitter.prototype).forEach(function (member) {
Doohickey.prototype[member] = EventEmitter.prototype[member];
});
function Doohickey() {
console.log('Doohickey constructed');
Gizmo.call(this); // initialize base class
EventEmitter.call(this); // initialize interface
}
Doohickey.prototype.turlywoops = function () {
console.log('turlywoops');
};
var myOwnDoohickey = new Doohickey();
// member function works
myOwnDoohickey.turlywoops();
// inherited member function works
myOwnDoohickey.wamboozle();
// interface member functions work
myOwnDoohickey.on('finagle', function (trick) {
console.log(trick);
});
myOwnDoohickey.emit('finagle', {
hello: 'world!'
});
// both true
console.log(myOwnDoohickey instanceof Doohickey);
console.log(myOwnDoohickey instanceof Gizmo);
// don't mind if this isn't necessarily true, though it would be nice
console.log(myOwnDoohickey instanceof EventEmitter);
Using something like underscore.js, you could create a new object based on two unrelated prototypes and use it as a prototype. In this example, properties/methods defined in obj2 will overwrite any in obj1 in the result object.
function IAmMulti(){
}
IAmMulti.prototype=_.extend(_.clone(Obj1.prototype),_.clone(Obj2.prototype));
Here's an example of that: JavaScript inheritance with _.extend()
You can't inherit more than 1 prototype at any level (you can have a stack of inheritance though), and interfaces have no meaning since javascript is a dynamic language and the entire prototype chain is searched for matching names. There's no notion of accessing an object through an interface.
In JavaScript you can define up to one Object which will be inherited by your Object. That Object's inheritance is also inherited by your object, etc, in a long chain.
function Foo() {
this.fooThisProp = 'tfoo';
}
Foo.prototype = Object.create(null);
Foo.prototype.fooProtoProp = 'pfoo';
function Bar() {
Foo.call(this);
this.barThisProp = 'tbar';
}
Bar.prototype = Object.create(Foo.prototype);
Bar.prototype.barProtoProp = 'pbar';
function Baz() {
Bar.call(this);
this.bazThisProp = 'tbaz';
}
Baz.prototype = Object.create(Bar.prototype);
Baz.prototype.bazProtoProp = 'pbaz';
var obj = new Baz();
obj; // {barThisProp: "tbar", bazThisProp: "tbaz", fooThisProp: "tfoo"}
obj.bazProtoProp; // "pbaz"
obj.barProtoProp; // "pbar"
obj.fooProtoProp; // "pfoo"
obj instanceof Baz; // true
obj instanceof Bar; // true
obj instanceof Foo; // true
You could always apply a constructor to an Object which isn't an instance so wouldn't inherit from that constructor. Just be careful the constructor doesn't assume the existance of inherited methods etc,
var fizz = {};
Bar.call(fizz);
fizz; // {barThisProp: "tbar", fooThisProp: "tfoo"}
fizz.barProtoProp; // undefined
fizz.fooProtoProp; // undefined
fizz instanceof Bar; // false
fizz instanceof Foo; // false
If you want to write a method wrapper to do things then you can use pretty much any Object in any context
function Buzz() {}
Buzz.prototype = Object.create(null); // Buzz separate from Foo, Bar, Baz
Buzz.prototype.bazLook = function (key) {
return Baz.prototype[key]; // or do something else with the value
}
var buzz = new Buzz();
buzz.bazLook('fooProtoProp'); // "pfoo"

Simplest/cleanest way to implement a singleton in JavaScript

What is the simplest/cleanest way to implement the singleton pattern in JavaScript?
I think the easiest way is to declare a simple object literal:
var myInstance = {
method1: function () {
// ...
},
method2: function () {
// ...
}
};
If you want private members on your singleton instance, you can do something like this:
var myInstance = (function() {
var privateVar = '';
function privateMethod () {
// ...
}
return { // public interface
publicMethod1: function () {
// All private members are accessible here
},
publicMethod2: function () {
}
};
})();
This has been called the module pattern, and it basically allows you to encapsulate private members on an object, by taking advantage of the use of closures.
If you want to prevent the modification of the singleton object, you can freeze it, using the ES5 Object.freeze method.
That will make the object immutable, preventing any modification to the its structure and values.
If you are using ES6, you can represent a singleton using ES Modules very easily, and you can even hold private state by declaring variables at the module scope:
// my-singleton.js
const somePrivateState = []
function privateFn () {
// ...
}
export default {
method1() {
// ...
},
method2() {
// ...
}
}
Then you can simply import the singleton object to use it:
import myInstance from './my-singleton.js'
// ...
I think the cleanest approach is something like:
var SingletonFactory = (function(){
function SingletonClass() {
//do stuff
}
var instance;
return {
getInstance: function(){
if (instance == null) {
instance = new SingletonClass();
// Hide the constructor so the returned object can't be new'd...
instance.constructor = null;
}
return instance;
}
};
})();
Afterwards, you can invoke the function as
var test = SingletonFactory.getInstance();
I'm not sure I agree with the module pattern being used as a replacement for a singleton pattern. I've often seen singletons used and abused in places where they're wholly unnecessary, and I'm sure the module pattern fills many gaps where programmers would otherwise use a singleton. However, the module pattern is not a singleton.
Module pattern:
var foo = (function () {
"use strict";
function aPrivateFunction() {}
return { aPublicFunction: function () {...}, ... };
}());
Everything initialized in the module pattern happens when Foo is declared. Additionally, the module pattern can be used to initialize a constructor, which could then be instantiated multiple times. While the module pattern is the right tool for many jobs, it's not equivalent to a singleton.
Singleton pattern:
short form
var Foo = function () {
"use strict";
if (Foo._instance) {
// This allows the constructor to be called multiple times
// and refer to the same instance. Another option is to
// throw an error.
return Foo._instance;
}
Foo._instance = this;
// Foo initialization code
};
Foo.getInstance = function () {
"use strict";
return Foo._instance || new Foo();
}
long form, using module pattern
var Foo = (function () {
"use strict";
var instance; //prevent modification of "instance" variable
function Singleton() {
if (instance) {
return instance;
}
instance = this;
//Singleton initialization code
}
// Instance accessor
Singleton.getInstance = function () {
return instance || new Singleton();
}
return Singleton;
}());
In both versions of the singleton pattern that I've provided, the constructor itself can be used as the accessor:
var a,
b;
a = new Foo(); // Constructor initialization happens here
b = new Foo();
console.log(a === b); //true
If you don't feel comfortable using the constructor this way, you can throw an error in the if (instance) statement, and stick to using the long form:
var a,
b;
a = Foo.getInstance(); // Constructor initialization happens here
b = Foo.getInstance();
console.log(a === b); // true
I should also mention that the singleton pattern fits well with the implicit constructor function pattern:
function Foo() {
if (Foo._instance) {
return Foo._instance;
}
// If the function wasn't called as a constructor,
// call it as a constructor and return the result
if (!(this instanceof Foo)) {
return new Foo();
}
Foo._instance = this;
}
var f = new Foo(); // Calls Foo as a constructor
-or-
var f = Foo(); // Also calls Foo as a constructor
In ES6 the right way to do this is:
class MyClass {
constructor() {
if (MyClass._instance) {
throw new Error("Singleton classes can't be instantiated more than once.")
}
MyClass._instance = this;
// ... Your rest of the constructor code goes after this
}
}
var instanceOne = new MyClass() // Executes succesfully
var instanceTwo = new MyClass() // Throws error
Or, if you don't want an error to be thrown on the second instance creation, you can just return the last instance, like so:
class MyClass {
constructor() {
if (MyClass._instance) {
return MyClass._instance
}
MyClass._instance = this;
// ... Your rest of the constructor code goes after this
}
}
var instanceOne = new MyClass()
var instanceTwo = new MyClass()
console.log(instanceOne === instanceTwo) // Logs "true"
In ECMAScript 2015 (ES6):
class Singleton {
constructor () {
if (!Singleton.instance) {
Singleton.instance = this
}
// Initialize object
return Singleton.instance
}
// Properties & Methods
}
const instance = new Singleton()
Object.freeze(instance)
export default instance
If you're using node.JS then you can take advantage of node.JS caching mechanism and your Singleton will be as simple as:
class Singleton {
constructor() {
this.message = 'I am an instance';
}
}
module.exports = new Singleton();
Please note that we export not the class Singleton but instance Singleton().
Node.JS will cache and reuse the same object each time it’s required.
For more details please check: Node.JS and Singleton Pattern
The following works in Node.js version 6:
class Foo {
constructor(msg) {
if (Foo.singleton) {
return Foo.singleton;
}
this.msg = msg;
Foo.singleton = this;
return Foo.singleton;
}
}
We test:
const f = new Foo('blah');
const d = new Foo('nope');
console.log(f); // => Foo { msg: 'blah' }
console.log(d); // => Foo { msg: 'blah' }
The simplest/cleanest for me means also simply to understand and no bells & whistles as are much discussed in the Java version of the discussion:
What is an efficient way to implement a singleton pattern in Java?
The answer that would fit simplest/cleanest best there from my point of view is:
Jonathan's answer to What is an efficient way to implement a singleton pattern in Java?
And it can only partly be translated to JavaScript. Some of the difference in JavaScript are:
constructors can't be private
Classes can't have declared fields
But given the latest ECMA syntax, it is possible to get close with:
Singleton pattern as a JavaScript class example
class Singleton {
constructor(field1,field2) {
this.field1=field1;
this.field2=field2;
Singleton.instance=this;
}
static getInstance() {
if (!Singleton.instance) {
Singleton.instance=new Singleton('DefaultField1','DefaultField2');
}
return Singleton.instance;
}
}
Example Usage
console.log(Singleton.getInstance().field1);
console.log(Singleton.getInstance().field2);
Example Result
DefaultField1
DefaultField2
If you want to use classes:
class Singleton {
constructor(name, age) {
this.name = name;
this.age = age;
if(this.constructor.instance)
return this.constructor.instance;
this.constructor.instance = this;
}
}
let x = new Singleton('s', 1);
let y = new Singleton('k', 2);
Output for the above will be:
console.log(x.name, x.age, y.name, y.age) // s 1 s 1
Another way of writing Singleton using function
function AnotherSingleton (name,age) {
this.name = name;
this.age = age;
if(this.constructor.instance)
return this.constructor.instance;
this.constructor.instance = this;
}
let a = new AnotherSingleton('s', 1);
let b = new AnotherSingleton('k', 2);
Output for the above will be:
console.log(a.name, a.age, b.name, b.age) // s 1 s 1
There is more than one way to skin a cat :) Depending on your taste or specific need you can apply any of the proposed solutions. I personally go for Christian C. Salvadó's first solution whenever possible (when you don't need privacy).
Since the question was about the simplest and cleanest, that's the winner. Or even:
var myInstance = {}; // Done!
This (quote from my blog)...
var SingletonClass = new function() {
this.myFunction() {
// Do stuff
}
this.instance = 1;
}
doesn't make much sense (my blog example doesn't either) because it doesn't need any private variables, so it's pretty much the same as:
var SingletonClass = {
myFunction: function () {
// Do stuff
},
instance: 1
}
I deprecate my answer, see my other one.
Usually the module pattern (see Christian C. Salvadó's answer) which is not the singleton pattern is good enough. However, one of the features of the singleton is that its initialization is delayed till the object is needed. The module pattern lacks this feature.
My proposition (CoffeeScript):
window.singleton = (initializer) ->
instance = undefined
() ->
return instance unless instance is undefined
instance = initializer()
Which compiled to this in JavaScript:
window.singleton = function(initializer) {
var instance;
instance = void 0;
return function() {
if (instance !== void 0) {
return instance;
}
return instance = initializer();
};
};
Then I can do following:
window.iAmSingleton = singleton(function() {
/* This function should create and initialize singleton. */
alert("creating");
return {property1: 'value1', property2: 'value2'};
});
alert(window.iAmSingleton().property2); // "creating" will pop up; then "value2" will pop up
alert(window.iAmSingleton().property2); // "value2" will pop up but "creating" will not
window.iAmSingleton().property2 = 'new value';
alert(window.iAmSingleton().property2); // "new value" will pop up
I got this example from the *JavaScript Patterns
Build Better Applications with Coding and Design Patterns book (by Stoyan Stefanov). In case you need some simple implementation class like a singleton object, you can use an immediate function as in the following:
var ClassName;
(function() {
var instance;
ClassName = function ClassName() {
// If the private instance variable is already initialized, return a reference
if(instance) {
return instance;
}
// If the instance is not created, save a pointer of the original reference
// to the private instance variable.
instance = this;
// All constructor initialization will be here
// i.e.:
this.someProperty = 0;
this.someMethod = function() {
// Some action here
};
};
}());
And you can check this example by following test case:
// Extending defined class like singleton object using the new prototype property
ClassName.prototype.nothing = true;
var obj_1 = new ClassName();
// Extending the defined class like a singleton object using the new prototype property
ClassName.prototype.everything = true;
var obj_2 = new ClassName();
// Testing makes these two objects point to the same instance
console.log(obj_1 === obj_2); // Result is true, and it points to the same instance object
// All prototype properties work
// no matter when they were defined
console.log(obj_1.nothing && obj_1.everything
&& obj_2.nothing && obj_2.everything); // Result true
// Values of properties which are defined inside of the constructor
console.log(obj_1.someProperty); // Outputs 0
console.log(obj_2.someProperty); // Outputs 0
// Changing property value
obj_1.someProperty = 1;
console.log(obj_1.someProperty); // Output 1
console.log(obj_2.someProperty); // Output 1
console.log(obj_1.constructor === ClassName); // Output true
This approach passes all test cases while a private static implementation will fail when a prototype extension is used (it can be fixed, but it will not be simple) and a public static implementation less advisable due to an instance is exposed to the public.
jsFiddly demo.
Short answer:
Because of the non-blocking nature of JavaScript, singletons in JavaScript are really ugly in use. Global variables will give you one instance through the whole application too without all these callbacks, and module pattern gently hides internals behind the interface. See Christian C. Salvadó's answer.
But, since you wanted a singleton…
var singleton = function(initializer) {
var state = 'initial';
var instance;
var queue = [];
var instanceReady = function(createdInstance) {
state = 'ready';
instance = createdInstance;
while (callback = queue.shift()) {
callback(instance);
}
};
return function(callback) {
if (state === 'initial') {
state = 'waiting';
queue.push(callback);
initializer(instanceReady);
} else if (state === 'waiting') {
queue.push(callback);
} else {
callback(instance);
}
};
};
Usage:
var singletonInitializer = function(instanceReady) {
var preparedObject = {property: 'value'};
// Calling instanceReady notifies the singleton that the instance is ready to use
instanceReady(preparedObject);
}
var s = singleton(singletonInitializer);
// Get the instance and use it
s(function(instance) {
instance.doSomething();
});
Explanation:
Singletons give you more than just one instance through the whole application: their initialization is delayed till the first use. This is really a big thing when you deal with objects whose initialization is expensive. Expensive usually means I/O and in JavaScript I/O always mean callbacks.
Don't trust answers which give you interface like instance = singleton.getInstance(), they all miss the point.
If they don't take a callback to be run when an instance is ready, then they won't work when the initializer does I/O.
Yeah, callbacks always look uglier than a function call which immediately returns an object instance. But again: when you do I/O, callbacks are obligatory. If you don't want to do any I/O, then instantiation is cheap enough to do it at program start.
Example 1, cheap initializer:
var simpleInitializer = function(instanceReady) {
console.log("Initializer started");
instanceReady({property: "initial value"});
}
var simple = singleton(simpleInitializer);
console.log("Tests started. Singleton instance should not be initalized yet.");
simple(function(inst) {
console.log("Access 1");
console.log("Current property value: " + inst.property);
console.log("Let's reassign this property");
inst.property = "new value";
});
simple(function(inst) {
console.log("Access 2");
console.log("Current property value: " + inst.property);
});
Example 2, initialization with I/O:
In this example, setTimeout fakes some expensive I/O operation. This illustrates why singletons in JavaScript really need callbacks.
var heavyInitializer = function(instanceReady) {
console.log("Initializer started");
var onTimeout = function() {
console.log("Initializer did his heavy work");
instanceReady({property: "initial value"});
};
setTimeout(onTimeout, 500);
};
var heavy = singleton(heavyInitializer);
console.log("In this example we will be trying");
console.log("to access singleton twice before it finishes initialization.");
heavy(function(inst) {
console.log("Access 1");
console.log("Current property value: " + inst.property);
console.log("Let's reassign this property");
inst.property = "new value";
});
heavy(function(inst) {
console.log("Access 2. You can see callbacks order is preserved.");
console.log("Current property value: " + inst.property);
});
console.log("We made it to the end of the file. Instance is not ready yet.");
I think I have found the cleanest way to program in JavaScript, but you'll need some imagination. I got this idea from a working technique in the book JavaScript: The Good Parts.
Instead of using the new keyword, you could create a class like this:
function Class()
{
var obj = {}; // Could also be used for inheritance if you don't start with an empty object.
var privateVar;
obj.publicVar;
obj.publicMethod = publicMethod;
function publicMethod(){}
function privateMethod(){}
return obj;
}
You can instantiate the above object by saying:
var objInst = Class(); // !!! NO NEW KEYWORD
Now with this work method in mind, you could create a singleton like this:
ClassSingleton = function()
{
var instance = null;
function Class() // This is the class like the above one
{
var obj = {};
return obj;
}
function getInstance()
{
if( !instance )
instance = Class(); // Again no 'new' keyword;
return instance;
}
return { getInstance : getInstance };
}();
Now you can get your instance by calling
var obj = ClassSingleton.getInstance();
I think this is the neatest way as the complete "Class" is not even accessible.
Christian C. Salvadó's and zzzzBov's answer have both given wonderful answers, but just to add my own interpretation based on my having moved into heavy Node.js development from PHP/Zend Framework where singleton patterns were common.
The following, comment-documented code is based on the following requirements:
one and only one instance of the function object may be instantiated
the instance is not publicly available and may only be accessed through a public method
the constructor is not publicly available and may only be instantiated if there is not already an instance available
the declaration of the constructor must allow its prototype chain to be modified. This will allow the constructor to inherit from other prototypes, and offer "public" methods for the instance
My code is very similar to zzzzBov's answer except I've added a prototype chain to the constructor and more comments that should help those coming from PHP or a similar language translate traditional OOP to JavaScript's prototypical nature. It may not be the "simplest" but I believe it is the most proper.
// Declare 'Singleton' as the returned value of a self-executing anonymous function
var Singleton = (function () {
"use strict";
// 'instance' and 'constructor' should not be available in a "public" scope
// here they are "private", thus available only within
// the scope of the self-executing anonymous function
var _instance=null;
var _constructor = function (name) {
this.name = name || 'default';
}
// Prototypes will be "public" methods available from the instance
_constructor.prototype.getName = function () {
return this.name;
}
// Using the module pattern, return a static object
// which essentially is a list of "public static" methods
return {
// Because getInstance is defined within the same scope
// it can access the "private" 'instance' and 'constructor' vars
getInstance:function (name) {
if (!_instance) {
console.log('creating'); // This should only happen once
_instance = new _constructor(name);
}
console.log('returning');
return _instance;
}
}
})(); // Self execute
// Ensure 'instance' and 'constructor' are unavailable
// outside the scope in which they were defined
// thus making them "private" and not "public"
console.log(typeof _instance); // undefined
console.log(typeof _constructor); // undefined
// Assign instance to two different variables
var a = Singleton.getInstance('first');
var b = Singleton.getInstance('second'); // passing a name here does nothing because the single instance was already instantiated
// Ensure 'a' and 'b' are truly equal
console.log(a === b); // true
console.log(a.getName()); // "first"
console.log(b.getName()); // Also returns "first" because it's the same instance as 'a'
Note that technically, the self-executing anonymous function is itself a singleton as demonstrated nicely in the code provided by Christian C. Salvadó. The only catch here is that it is not possible to modify the prototype chain of the constructor when the constructor itself is anonymous.
Keep in mind that to JavaScript, the concepts of “public” and “private” do not apply as they do in PHP or Java. But we have achieved the same effect by leveraging JavaScript’s rules of functional scope availability.
You could just do:
var singleton = new (function() {
var bar = 123
this.foo = function() {
// Whatever
}
})()
The clearest answer should be this one from the book Learning JavaScript Design Patterns by Addy Osmani.
var mySingleton = (function () {
// Instance stores a reference to the singleton
var instance;
function init() {
// Singleton
// Private methods and variables
function privateMethod(){
console.log( "I am private" );
}
var privateVariable = "I'm also private";
var privateRandomNumber = Math.random();
return {
// Public methods and variables
publicMethod: function () {
console.log( "The public can see me!" );
},
publicProperty: "I am also public",
getRandomNumber: function() {
return privateRandomNumber;
}
};
};
return {
// Get the singleton instance if one exists
// or create one if it doesn't
getInstance: function () {
if ( !instance ) {
instance = init();
}
return instance;
}
};
})();
For me the cleanest way to do so is:
const singleton = new class {
name = "foo"
constructor() {
console.log(`Singleton ${this.name} constructed`)
}
}
With this syntax you are certain your singleton is and will remain unique. You can also enjoy the sugarness of class syntax and use this as expected.
(Note that class fields require node v12+ or a modern browser.)
This is how I implement singleton pattern using ES6 features. Yes, I know this does not look like an Object-oriented approach, but I find this method is easy to implement and a clean way to implement.
const Singleton = (() => {
var _instance = !_instance && new Object('Object created....');
return () => _instance;
})();
//************************************************************************
var instance1 = Singleton();
var instance2 = Singleton();
console.log(instance1 === instance2); // true
This should work:
function Klass() {
var instance = this;
Klass = function () { return instance; }
}
I believe this is the simplest/cleanest and most intuitive way though it requires ECMAScript 2016 (ES7):
export default class Singleton {
static instance;
constructor(){
if(instance){
return instance;
}
this.state = "duke";
this.instance = this;
}
}
The source code is from: adam-bien.com
I've found the following to be the easiest singleton pattern, because using the new operator makes this immediately available within the function, eliminating the need to return an object literal:
var singleton = new (function () {
var private = "A private value";
this.printSomething = function() {
console.log(private);
}
})();
singleton.printSomething();
Using ES6 classes and private static fields. Invoking new instances of the Singleton class will return the same instance. The instance variable is also private and can't be accessed outside the class.
class Singleton {
// # is a new Javascript feature that denotes private
static #instance;
constructor() {
if (!Singleton.#instance) {
Singleton.#instance = this
}
return Singleton.#instance
}
get() {
return Singleton.#instance;
}
}
const a = new Singleton();
const b = new Singleton();
console.log(a.get() === b.get()) // true
console.log(Singleton.instance === undefined) // true
function Once() {
return this.constructor.instance || (this.constructor.instance = this);
}
function Application(name) {
let app = Once.call(this);
app.name = name;
return app;
}
If you are into classes:
class Once {
constructor() {
return this.constructor.instance || (this.constructor.instance = this);
}
}
class Application extends Once {
constructor(name) {
super();
this.name = name;
}
}
Test:
console.log(new Once() === new Once());
let app1 = new Application('Foobar');
let app2 = new Application('Barfoo');
console.log(app1 === app2);
console.log(app1.name); // Barfoo
Following is the snippet from my walkthrough to implement a singleton pattern. This occurred to me during an interview process and I felt that I should capture this somewhere.
/*************************************************
* SINGLETON PATTERN IMPLEMENTATION *
*************************************************/
// Since there aren't any classes in JavaScript, every object
// is technically a singleton if you don't inherit from it
// or copy from it.
var single = {};
// Singleton Implementations
//
// Declaring as a global object...you are being judged!
var Logger = function() {
// global_log is/will be defined in the GLOBAL scope here
if(typeof global_log === 'undefined'){
global_log = this;
}
return global_log;
};
// The below 'fix' solves the GLOABL variable problem, but
// the log_instance is publicly available and thus can be
// tampered with.
function Logger() {
if(typeof Logger.log_instance === 'undefined') {
Logger.log_instance = this;
}
return Logger.log_instance;
};
// The correct way to do it to give it a closure!
function logFactory() {
var log_instance; // Private instance
var _initLog = function() { // Private init method
log_instance = 'initialized';
console.log("logger initialized!")
}
return {
getLog : function(){ // The 'privileged' method
if(typeof log_instance === 'undefined') {
_initLog();
}
return log_instance;
}
};
}
/***** TEST CODE ************************************************
// Using the Logger singleton
var logger = logFactory(); // Did I just give LogFactory a closure?
// Create an instance of the logger
var a = logger.getLog();
// Do some work
// Get another instance of the logger
var b = logger.getLog();
// Check if the two logger instances are same
console.log(a === b); // true
*******************************************************************/
The same can be found on my gist page.
My two cents: I have a constructor function (CF), for example,
var A = function(arg1){
this.arg1 = arg1
};
I need just every object created by this CF to be the same.
var X = function(){
var instance = {};
return function(){ return instance; }
}();
Test
var x1 = new X();
var x2 = new X();
console.log(x1 === x2)
Singleton:
Ensure a class has only one instance and provides a global point of access to it.
The singleton pattern limits the number of instances of a particular object to just one. This single instance is called the singleton.
defines getInstance() which returns the unique instance.
responsible for creating and managing the instance object.
The singleton object is implemented as an immediate anonymous function. The function executes immediately by wrapping it in brackets followed by two additional brackets. It is called anonymous because it doesn't have a name.
Sample Program
var Singleton = (function () {
var instance;
function createInstance() {
var object = new Object("I am the instance");
return object;
}
return {
getInstance: function () {
if (!instance) {
instance = createInstance();
}
return instance;
}
};
})();
function run() {
var instance1 = Singleton.getInstance();
var instance2 = Singleton.getInstance();
alert("Same instance? " + (instance1 === instance2));
}
run()
Here is a simple example to explain the singleton pattern in JavaScript.
var Singleton = (function() {
var instance;
var init = function() {
return {
display:function() {
alert("This is a singleton pattern demo");
}
};
};
return {
getInstance:function(){
if(!instance){
alert("Singleton check");
instance = init();
}
return instance;
}
};
})();
// In this call first display alert("Singleton check")
// and then alert("This is a singleton pattern demo");
// It means one object is created
var inst = Singleton.getInstance();
inst.display();
// In this call only display alert("This is a singleton pattern demo")
// it means second time new object is not created,
// it uses the already created object
var inst1 = Singleton.getInstance();
inst1.display();
let MySingleton = (function () {
var _instance
function init() {
if(!_instance) {
_instance = { $knew: 1 }
}
return _instance
}
let publicAPIs = {
getInstance: function() {
return init()
}
}
// this prevents customize the MySingleton, like MySingleton.x = 1
Object.freeze(publicAPIs)
// this prevents customize the MySingleton.getInstance(), like MySingleton.getInstance().x = 1
Object.freeze(publicAPIs.getInstance())
return publicAPIs
})();
I needed several singletons with:
lazy initialisation
initial parameters
And so this was what I came up with:
createSingleton ('a', 'add', [1, 2]);
console.log(a);
function createSingleton (name, construct, args) {
window[name] = {};
window[construct].apply(window[name], args);
window[construct] = null;
}
function add (a, b) {
this.a = a;
this.b = b;
this.sum = a + b;
}
args must be Array for this to work, so if you have empty variables, just pass in []
I used the window object in the function, but I could have passed in a parameter to create my own scope
name and construct parameters are only String in order for window[] to work, but with some simple typechecking, window.name and window.construct are also possible.

Categories

Resources