Is Shenma Singleton mode? Simply put, a constructor has only one instance, no matter how many times you call this constructor to create an instance, for example:
Function class () {}// is used only for example var instance_01 = new class (); var instance_02 = new class (); console. log (instance_01 === instance_02); // output: True
We know that in Javascript, when and only whenInstance_01AndInstance_02PointSame Instance Object, The above expression can be output as true, in other words, that is:
IfInstance_01AndInstance_02Not to the same instance object, even ifInstance_01AndInstance_02With identical property values, the above expression also outputs false
You can perform a small test:
Function wife (name) {This. name = Name;} wife. prototype. shout = function () {console. log ('I \'m your only wife' + this. name + ', do remember! ') ;}; Var wife_01 = new wife ('marry'); var wife_02 = new wife ('Mary'); console. log (wife_01 ==== wife_02); // although the name is the same, the output is: false, and the wife actually has two days ~~
So how is the above example implemented?
The simplest and most intuitive way of thinking: When you call this constructor for the first time to create an instance object, you can save the reference of this instance object. Next, when this constructor is called again, no matter how many times, only the previously saved instance object is returned.
Still usedWifeExample:
Function wife (name) {If (wife. instance) {return wife. instance;} wife. instance = this; this. name = Name;} wife. prototype. shout = function () {console. log ('I \'m your only wife' + this. name + ', do remember! ') ;}; Var wife_01 = new wife ('marry'); wife_01.shout (); // output: I'm your only wife Marry, do remember! VaR wife_02 = new wife ('Lucy '); wife_02.shout (); // output: I'm your only wife Marry, do remember! Console. Log (wife_01 === wife_02); // output: True
Good. Now it's in line with the requirements of the One-wife system, but I always feel that something is wrong-if someoneWife. InstanceThe tragedy was not long after the malicious modification.
For this purpose, make a small patch:
VaR wife = (function () {var instance = NULL; // external access is not allowed, so VaR _ wife = function (name) {If (Instance) is secure) {return instance;} instance = this; this. name = Name;} return _ wife;}) (); Wife. prototype. shout = function () {console. log ('I \'m your only wife' + this. name + ', do remember! ') ;}; Var wife_01 = new wife ('marry'); wife_01.shout (); // output: I'm your only wife Marry, do remember! VaR wife_02 = new wife ('Lucy '); wife_02.shout (); // output: I'm your only wife Marry, do remember! Console. Log (wife_01 === wife_02); // output: True
Over