JavaScript single case mode (singleton in Javascript) _js object oriented

Source: Internet
Author: User
The basic structure of a single case pattern:
Copy Code code as follows:

Mynamespace.singleton = function () {
return {};
}();

Like what:
Copy Code code as follows:

Mynamespace.singleton = (function () {
return {//public members.
Publicattribute1:true,
Publicattribute2:10,
Publicmethod1:function () {
...
},
Publicmethod2:function (args) {
...
}
};
})();

However, the above Singleton is already established when the code is loaded, how to delay loading? Imagine how to implement a single example in C #: Use the following pattern:
Copy Code code as follows:

Mynamespace.singleton = (function () {
function constructor () {//All of the ' normal singleton code goes here.
...
}
return {
Getinstance:function () {
Control code goes here.
}
}
})();

Specifically, the code that creates the singleton is put into the constructor, and then instantiated at the first call:
The complete code is as follows:
Copy Code code as follows:

Mynamespace.singleton = (function () {
var uniqueinstance;//Private ATT Ribute 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;
}
}
}) ();

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.