JSFiddle - React, Tailwind, and code Playground
JavaScript
var Person = (function(){
// Self calling function
// Private property for holding the only existing instance
var personInstance;
var createPerson = function(){
// Private property initializing default pull capacity.
var canPullWeight = 3;
// Private method for increasing the value of canPullWeight.
var canPull = function( kg ){
canPullWeight = kg;
};
// Private method for passing increased value.
var increaseEnergy = function( newVal ){
canPull( newVal );
};
// Private method for returning value of return canPullWeight,
// at any point of time, from the one and only existing instance.
var pullCapacity = function(){
return canPullWeight;
};
return {
// returns increaseEnergy method which is a
// closure with access to private properties.
increaseEnergy: increaseEnergy,
getPullCapacity: pullCapacity
};
};
return {
// Method for creating instance of Person.
getInstance: function(){
// Condition checking existence of instance
if(!personInstance){
personInstance = createPerson();
}
// If instance already existing returning the same.
return personInstance;
}
};
})( );
// Creating firstPerson instance.
var firstPerson = Person.getInstance( );
// alerts default value 3.
alert(firstPerson.getPullCapacity());
// Creating secondPerson instance (Same instance is used)
var secondPerson = Person.getInstance();
// Same output. Alerts default value 3.
alert(secondPerson.getPullCapacity());
// Calling increaseEnergy Method of firstPerson with newVal as 20.
// Note: we are not going to call increaseEnergy method of secondPerson.
firstPerson.increaseEnergy( 20 );
// alerts new value which is 20.
alert(firstPerson.getPullCapacity());
// It also alerts new value which is 20, as same instance is used
alert(secondPerson.getPullCapacity());