JavaScript design Pattern---(Singleton mode learning)

Source: Internet
Author: User

Single-Case mode

A class can have only one instantiated object. such as the PopOver layer on the page, one page only needs one.

Implementation: Create a class that contains a method that creates a new instance object without the presence of an object. If the object exists, this object simply returns a reference to the object.

varSingleton = (functionSingleton () {varInstance =NULL;//Store a reference to a singleton instance
Create a single casefunctionInit () {
Private methods and propertiesfunctionPrivatemethod () {Console.log (' This is a private method! ') } varprivatevariable = ' I am a private variable! 'return {
Public methods and properties Publicmethod:function() {Console.log (' Public ')}, Getprivatevariable:function () { returnPrivatevariable}} } return{getinstance:function () { if(!instance) {Instance=init (); } returninstance; } }})();

This method is not abstract enough, if we need to create a singleton function changes? So we further abstract functions

var function (FN) {    varnull;     return function () {        return Instance | | Fn.call (this, arguments)    }}

JavaScript design Pattern---(Singleton mode learning)

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.