Singleton in Javascript

Source: Internet
Author: User

The author of Parctical Common Lisp has said that if you need a pattern, there must be something wrong. The problem he says is that because of the innate flaws of language, he has to seek and summarize a common solution.

Whether it is a weak or strong type, static or dynamic languages, imperative or descriptive languages, and each language has inherent advantages and disadvantages. A Jamaican athlete, who has some advantages in sprint and even boxing, lacks some in yoga practice.

Warlocks and Shadow priests can easily be an excellent aid, and an enemy law that flies on the map with Macon will be slightly awkward. In the program, the static language may need to spend a lot of effort to achieve the decorator, and JS because can at any time to throw the object above the method, so that the decorator mode in JS into a chicken.

There are fewer books about JavaScript design patterns. Pro javaScript Design Patterns. is a relatively classic one, but its examples are more verbose, so combined with the code I wrote at work, summed up my understanding. If there is a discrepancy in my understanding, please do not hesitate to correct me.

A single case pattern

The singleton pattern is defined as a unique instance of a class, but JS itself is a "no class" language. Many of the JS design patterns of the article put {} as a single case to use also reluctantly made sense. Because JS generates objects in a variety of ways, let's look at another more meaningful single case.

There is a common need to click on a button when you need to pop up a mask layer on the page. For example web.qq.com click Log in time.

The code that generates the gray background matte layer is very well written.

var function () {   return  document.body.appendChild (  document.createelement (div)  );} $ (' button '). Click (function() {   var mask = createmask ();   Mask.show ();})

The problem is that this mask layer is globally unique, so every call to Createmask creates a new div, although it can be removed from the hidden mask layer. But obviously it is unreasonable to do so.

Look at the second scenario and create the div at the beginning of the page. It is then referenced with a variable.

var mask = document.body.appendChild (document.createelement (' div ') ); $ (' button '). Click (  function() {   mask.show ();})

This really creates a mask layer div on the page, but another problem comes up, and maybe we'll never need this mask layer, which wastes a div and should be very stingy with any operation on the DOM node.

If you can use a variable. To determine if a DIV has been created?

var Mask; var function () {ifreturn  mask; Else  = document,body.appendchild (  document.createelement (div)  return  Mask;}}

It looks good, and here it does complete a function that produces a single-column object. Let's take a closer look at what's wrong with this piece of code.

first of all, this function has some side effects, the function body changes the external variable mask reference, In a multi-person collaborative project, Createmask is an unsafe function. On the other hand, mask, the global variable, is not necessary. Let's improve it a little bit .

var function () {  var  mask;   return function () {       return Mask | | (Mask = document.body.appendChild (document.createelement (' div.))  }} ();

Use a simple closure to wrap the variable mask, at least for the Createmask function, it is closed.

The 23 design patterns in Gof are also long-existing and reusable patterns in software development. If the programmer does not explicitly realize that he has used certain patterns, he may miss a more appropriate design next time (this is from "As's Program World").

Come back to the point, the front of the single case is still flawed. It can only be used to create a matte layer. What if I need to write a function to create a unique XHR object? Can you find a generic singleton wrapper?

The function in JS is the first type, which means that the function can also be passed as a parameter. Look at the final code.

var function (FN) {     var  result;     return function () {        return Result | | (Result = fn.apply (this, arguments));}    } var createmask = Singleton (function() {return document.body.appendChild (Document.createelement (' div '));});

A variable is used to hold the return value for the first time, and if it has already been assigned, the variable will be returned in precedence in subsequent calls. The code that actually creates the mask layer is passed to the Singleton wrapper in the form of a callback function. This method is actually called bridging mode. About bridging mode, put it in the back a little bit.

However, the Singleton function is not perfect, and it always requires a variable result to register a reference to the Div. Unfortunately, the functional nature of JS is not enough to completely eliminate declarations and statements.

Singleton in Javascript

Related Article

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.