JavaScript design mode-Singleton mode

Source: Internet
Author: User

The singleton mode, which is a kind of creation design pattern, is also called the monomer pattern, which is only allowed to instantiate the object class once. Sometimes it is also used to plan a namespace.

1 varUtil = {2GetName:function () {3Console.log (' WP ')4     },5Getage:function () {6Console.log (25)7     },8GETALL:function () {9          This. GetName ();Ten          This. Getage (); One     } A } -Wang.getall ()

In addition to defining namespaces, you can manage the individual modules of the code base.

Cases:

1 varUtil = {2 Tool: {3Tool1:function () {4             ...5         },6Too2:function () {7             ...8         }9     },Ten Ajax: { OneGetfunction () { A             ... -         }, -Postfunction () { the             ... -         } -     }, - Animate: { +Movefunction () { -             ... +         }, ARotatefunction () { at             ... -         } -     } - } -Util.Tool.tool1 ();

exceptions, using singleton mode, you can also set static variables that cannot be modified

 var  Conf = (function   () { var  conf = {conf_ A:  100 200 300}  return   {get:  function   return  conf[name]? Conf[name]: null  }}) ();  var  conf_a = conf.get (' conf_a '  //  

Description: Because static variables are defined in the function object, and only the Get method is provided inside the function, these static variables can only be accessed externally through privileged methods, but these static variables cannot be modified

JavaScript design mode-Singleton mode

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.