Copy Code code as follows:
/* Basic Singleton. */
var Singleton = {
Attribute1:true,
Attribute2:10,
Method1:function () {
},
Method2:function (ARG) {
}
};
One of the most important uses of a single piece mode is the namespace:
/* Giantcorp namespace. */
var Giantcorp = {};
Giantcorp.common = {
A Singleton with common methods used by the all objects and modules.
};
Giantcorp.errorcodes = {
An object literal used to store data.
};
Giantcorp.pagehandler = {
A Singleton with page specific methods and attributes.
};
Implement private and private variables in a single piece mode using closures:
Giantcorp.dataparser = (function () {
Private attributes.
var whitespaceregex =/\s+/;
Private methods.
function Stripwhitespace (str) {
Return Str.replace (Whitespaceregex, "");
}
function Stringsplit (str, delimiter) {
Return Str.split (delimiter);
}
Everything returned in the object literal are public, but can access the
Members in the closure created above.
return {
Public method.
Stringtoarray:function (str, delimiter, STRIPWS) {
if (STRIPWS) {
str = stripwhitespace (str);
}
var outputarray = stringsplit (str, delimiter);
return outputarray;
}
};
})(); Invoke the function and assign the returned object literal to
Giantcorp.dataparser.
Implement lazy instantiation Single-piece mode:
Mynamespace.singleton = (function () {
var uniqueinstance; Private attribute that holds the single instance.
function constructor () {//All of the ' normal singleton code goes here.
...
}
return {
Getinstance:function () {
if (!uniqueinstance) {//Instantiate only if the instance doesn ' t exist.
Uniqueinstance = Constructor ();
}
return uniqueinstance;
}
}
})();
MyNamespace.Singleton.getInstance (). PUBLICMETHOD1 ();