Reference resources: In-depth understanding of JavaScript series by Uncle Tom
A single example is to ensure that a class has only one instance, the method of implementation is generally first to determine whether the instance exists or not, if there is a direct return, if it does not exist to create a return, this ensures that a class has only one instance object.
The object literal is the simplest single-case pattern:
var mysingleton = { "a property", function () { Console.log ( "This is a method"); };
A simple single-case
varMysingleton = (function () { varinstance, init=function () { return{property:"A Property", Method:function () {} }; }; return{getinstance:function () { returninstance | | (Instance =init ()); } };}) ();varMysingle = Mysingleton.getinstance ();
Another single case
varMysingleton = (function () { varSingleton =function(args) {varargs = args | | {}; This. Name = "a singleton"; This. Pointx = Args.pointx | | 6; This. Pointy = Args.pointy | | 10; }; varinstance; varExports ={getinstance:function(args) {if(Instance = = =undefined) {Instance=NewSingleton (args); } returninstance; } }; returnexports;}) ();varMysingle =mysingleton.getinstance ({pointx:10, Pointy:10});
A single-instance pattern of JavaScript design patterns